Home >Backend Development >C++ >How Can I Convert a String to a Type in C#?

How Can I Convert a String to a Type in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-23 14:37:10108browse

How Can I Convert a String to a Type in C#?

String type conversion in C#

In C# programming, it is often necessary to dynamically convert a string representing a class name into its corresponding type. However, using Type.GetType("System.Int32") this default method only works for types located in mscorlib or in the calling assembly.

For classes located in other assemblies, a different approach is required. The required type can be successfully retrieved by including the assembly name in the string:

<code class="language-csharp">Type type = Type.GetType("命名空间.我的类, 我的程序集");</code>

If the assembly has a strong name, its details must be included. For more guidance, please refer to the Type.GetType(string) documentation.

Alternatively, assume you hold a reference to the target assembly, e.g. via a known type. In this case, Assembly.GetType provides a convenient solution:

<code class="language-csharp">Assembly asm = typeof(某个已知类型).Assembly;
Type type = asm.GetType(带命名空间的类型名称);</code>

Using the above techniques, you can easily implement string to type conversion in C#, thereby fully realizing the potential of dynamic type retrieval.

The above is the detailed content of How Can I Convert a String to a Type in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn