C# typeof:如何从字符串中获取类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15108786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typeof: how to get type from string
提问by Refael
I've many objects, each of which I have information in string about its type.
like:
我有很多对象,每个对象都有关于其类型的字符串信息。
喜欢:
string stringObjectType = "DateTime";
While running, I have no object itself.
So I can not test it typeof (object)
跑步时,我本身没有对象。
所以我无法测试typeof (object)
How can I get while running the type of the object by:
我如何在运行对象类型时通过以下方式获得:
typeof (stringObjectType)
采纳答案by HardLuck
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);
}
回答by PhonicUK
You can use Type.GetType()
to get a type from its string name. So you can do:
您可以使用Type.GetType()
从其字符串名称中获取类型。所以你可以这样做:
Type DateType = Type.GetType("System.DateTime");
You can't just use "DateTime" since that's not the type's name. If you do this and the name is wrong (it doesn't exist) then it'll throw an exception. So you'll need a try/catch around this.
您不能只使用“DateTime”,因为那不是类型的名称。如果您这样做并且名称错误(它不存在),那么它会抛出异常。所以你需要尝试/抓住这个。
You can get the proper type name for any given object by doing:
您可以通过执行以下操作获取任何给定对象的正确类型名称:
string TypeName = SomeObject.GetType().FullName;
If you need to use vague or incomplete names, then you're going to have a fun time messing around with reflection. Not impossible, but certainly a pain.
如果您需要使用模糊或不完整的名称,那么您将在思考中度过一段愉快的时光。并非不可能,但肯定是一种痛苦。