c# - 类型 : how to get type from string

标签 c# .net

我有很多对象,每个对象都有关于其类型的字符串信息。
喜欢:

string stringObjectType = "DateTime";

在运行时,我没有对象本身。
所以我无法测试它 typeof (object)

如何在运行时获取对象的类型:

typeof (stringObjectType)

最佳答案

try
{
    // Get the type of a specified class.
    Type myType1 = Type.GetType("System.DateTime");
    Console.WriteLine("The full name is {myType1.FullName}.");

    // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
    Type myType2 = Type.GetType("NoneSuch", true);
    Console.WriteLine("The full name is {myType2.FullName}.");
}
catch(TypeLoadException e)
{
    Console.WriteLine(e.Message);
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}

参见 Type.GetType(string) on MSDN

关于c# - 类型 : how to get type from string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15108786/

相关文章:

c# - 从实体中获取单列

c# - 如何从测试项目中获取项目路径?

c# - 匹配下划线前所有内容的正则表达式

c# - 如何在 C# 中编码 NDISUIO_QUERY_OID 结构以执行以下任务

c# - 如何防止任务的同步延续?

c# - 有没有办法获得唯一的计算机 ID?

c# - 从一个 Json 移植到 javas org.json.JSONObject,缺少键的行为不一样

.net - 在 Expression Blend 中反转剪切路径

c# - 如何在Azure Function中配置OpenApiRequestBody?

c# - 为什么 Thread.Sleep( ... ) 避免 CPU 使用基于多线程 Windows 服务的应用程序的 100% 重执行?