繁体   English   中英

有没有办法在 c# 中将“int”转换为 typeof(int)?

[英]Is there a way to convert "int" to typeof(int) in 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
   }        
});

要获取所有原始类型及其别名,您可以编写:

string assemblyFullName = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
var assembly = Assembly.Load(assemblyFullName);
var primitiveTypes =
    assembly.DefinedTypes.Where(definedType => definedType.IsPrimitive && definedType != typeof(IntPtr) && definedType != typeof(UIntPtr));

using (var provider = new CSharpCodeProvider())
{
    var result = primitiveTypes.Select(x => (Alias: provider.GetTypeOutput(new CodeTypeReference(x)), Type: x));
}

会导致:

bool    typeof(Boolean)
byte    typeof(Byte)
char    typeof(Char)
double  typeof(Double)
short   typeof(Int16)
int     typeof(Int32)
long    typeof(Int64)
sbyte   typeof(SByte)
float   typeof(Single)
ushort  typeof(UInt16)
uint    typeof(UInt32)
ulong   typeof(UInt64)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM