typeof:如何从字符串中获取类型

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

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 {0}.", 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 {0}.", myType2.FullName); } catch(TypeLoadException e) { Console.WriteLine(e.Message); } catch(Exception e) { Console.WriteLine(e.Message); } 

请参阅MSDN上的Type.GetType(string)

您可以使用Type.GetType()从其字符串名称中获取类型。 所以你可以这样做:

 Type DateType = Type.GetType("System.DateTime"); 

你不能只使用“DateTime”,因为那不是类型的名称。 如果你这样做并且名称错误(它不存在)那么它将抛出exception。 所以你需要尝试/捕捉这个。

您可以通过执行以下操作获取任何给定对象的正确类型名称:

 string TypeName = SomeObject.GetType().FullName; 

如果你需要使用模糊或不完整的名字,那么你将有一个充满乐趣的时间搞乱反思。 并非不可能,但肯定是一种痛苦。