有没有办法在c#中将“int”转换为typeof(int)?
c#
我知道我可以像这样从字符串名称中获取类型
Type intType = Type.GetType("System.Int32");
但是,如果我有这样的字符串怎么办
string[] typeNameArr = new string[] {"Int", "String", "DateTime", "Bool"};
如何将这些转换为实际类型?也许我可以从别名中获得完全限定的名称,然后执行GetType?
回答
如果您使用完全限定的名称,就像"System.Int32"最后您将能够通过 linq 使用它:
var types = typeNameArr.Select(c => Type.GetType(c));
另外:如果您的 Web 服务提供自定义名称,则您需要映射或约定。例如:
var types = typeNameArr.Select(c => Type.GetType("System." + c));
或者
var types = typeNameArr.Select(c =>
{
switch (c)
{
"Int":
return typeof(int);
"Foo":
return typeof(BarClass);
default:
return null
}
});
- @Talha: Since the [list of C# aliases](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types) fairly short and unlikely to change, I would definitely argue for a large, hard-coded `switch` statement rather than using some framework magic.
- You might as well do a mapping from `string` to `Type` at this point: `c switch { "Int" => typeof(int), ... }`