In C#, a string containing a type name can be converted into the corresponding Type object. However, the method used for this conversion depends on whether the type is defined in the same assembly as the calling code, or in a different assembly.
Type.GetType(string)
If the type is defined in the same assembly, you can use the Type.GetType(string)
method and provide the fully qualified type name as a string. For example, to get the int
of the Type
data type, you would use:
<code class="language-csharp">Type.GetType("System.Int32");</code>
Assembly.GetType(string)
If the type is defined in a different assembly, you also need to provide the assembly name. This can be achieved using the Assembly.GetType(string)
method. First, get a reference to the assembly, then use that reference to get the Type
:
<code class="language-csharp">Assembly asm = typeof(SomeKnownType).Assembly; Type type = asm.GetType("Namespace.MyClass");</code>
Make sure to include the type's namespace in the string provided to Type.GetType()
or Assembly.GetType()
. Additionally, for strong-named assemblies, it may be necessary to include the full assembly identity, including version, culture, and public key tags.
Consider the following scenario, where there is a string containing the fully qualified name of a type:
<code class="language-csharp">string typeName = "Namespace.MyClass, MyAssembly";</code>
Depending on whether MyAssembly
is referenced by the calling assembly, either Type.GetType()
or Assembly.GetType()
can be used:
<code class="language-csharp">// 如果 MyAssembly 被引用 Type type1 = Type.GetType(typeName); // 如果 MyAssembly 未被引用 Assembly asm = typeof(SomeKnownType).Assembly; Type type2 = asm.GetType(typeName);</code>
The above is the detailed content of How to Determine Object Type from its String Representation in C#?. For more information, please follow other related articles on the PHP Chinese website!