typeof:如何从字符串获取类型 [英] typeof: how to get type from string
本文介绍了typeof:如何从字符串获取类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多对象,每个对象都有关于类型的字符串信息。
如:
I've many objects, each of which I have information in string about its type.
like:
string stringObjectType = "DateTime";
在运行时,我本身没有对象。
所以我无法测试它 typeof(object)
While running, I have no object itself.
So I can not test it typeof (object)
在运行对象类型时如何获得:
How can I get while running the type of the object by:
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);
}
请参见在MSDN上的 Type.GetType(string)
这篇关于typeof:如何从字符串获取类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文