将字符串转换为 C# 中的类型
如果我收到一个包含类名的字符串,我想将此字符串转换为真实类型(字符串中的类型),我该怎么做?
If I receive a string that contains the name of a class and I want to convert this string to a real type (the one in the string), how can I do this?
我试过了
Type.GetType("System.Int32")
例如,它似乎有效.
但是当我尝试使用自己的对象时,它总是返回 null ...
But when I try with my own object, it always returns null ...
我事先不知道字符串中的内容,因此它是我将其转换为实际类型的唯一来源.
I have no idea what will be in the string in advance so it's my only source for converting it to its real type.
Type.GetType("NameSpace.MyClasse");
有什么想法吗?
如果类型在 中,您只能使用只是类型的名称(当然还有它的命名空间)mscorlib
或调用程序集.否则,您还必须包含程序集名称:
You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib
or the calling assembly. Otherwise, you've got to include the assembly name as well:
Type type = Type.GetType("Namespace.MyClass, MyAssembly");
如果程序集是强命名的,则您还必须包含所有这些信息.请参阅Type.GetType(string)
的文档a> 了解更多信息.
If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string)
for more information.
或者,如果您已经有对程序集的引用(例如通过众所周知的类型),您可以使用 Assembly.GetType
:
Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType
:
Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);