2009-09-22 138 views
2

是否存在一个函数,如果C#类型的字符串表示形式返回相应的.Net类型或.Net类型的字符串表示形式;或以任何方式来实现这一点。通过反射获取.Net对应类型的C#类型

例如:

“布尔” - > System.Boolean或 “System.Boolean”

“INT” - > System.Int32或 “System.Int32”

...

谢谢。

编辑:真的很抱歉,它不是我想要的“类型到类型”映射,而是“字符串到字符串”映射或“字符串到类型”映射。

+0

严重嗨 - 我更新你标题去掉你把在它开始的标签。因为你非常贴心地标记了你的问题,所以不需要它们。 – 2011-01-09 07:01:45

+0

@Michael:谢谢,那时候我习惯了传统的论坛,你在标题中明确地指定了标签:) – Pragmateek 2011-01-10 21:59:09

回答

6

list of built-in types in C#是相当短的,不太可能改变,所以我认为有一个字典或大switch声明映射这些应该不难以维护。

如果你想支持可空类型,我相信你有没有其他的选择,而不是解析输入字符串:

static Type GetTypeFromNullableAlias(string name) 
{ 
    if (name.EndsWith("?")) 
     return typeof(Nullable<>).MakeGenericType(
      GetTypeFromAlias(name.Substring(0, name.Length - 1))); 
    else 
     return GetTypeFromAlias(name); 
} 

static Type GetTypeFromAlias(string name) 
{ 
    switch (name) 
    { 
     case "bool": return typeof(System.Boolean); 
     case "byte": return typeof(System.Byte); 
     case "sbyte": return typeof(System.SByte); 
     case "char": return typeof(System.Char); 
     case "decimal": return typeof(System.Decimal); 
     case "double": return typeof(System.Double); 
     case "float": return typeof(System.Single); 
     case "int": return typeof(System.Int32); 
     case "uint": return typeof(System.UInt32); 
     case "long": return typeof(System.Int64); 
     case "ulong": return typeof(System.UInt64); 
     case "object": return typeof(System.Object); 
     case "short": return typeof(System.Int16); 
     case "ushort": return typeof(System.UInt16); 
     case "string": return typeof(System.String); 
     default: throw new ArgumentException(); 
    } 
} 

测试:

GetTypeFromNullableAlias("int?").Equals(typeof(int?)); // true 
3

你的问题并不完全清楚:我不确定你为C#别名得到了什么样的表单。如果你在编译时知道它,你可以像平常一样使用typeof() - C#别名确实是只是别名,所以typeof(int) == typeof(System.Int32)。有没有排放代码的区别。

如果你有一个字符串,例如"int",只是建立一个地图:

Dictionary<string,Type> CSharpAliasToType = new Dictionary<string,Type> 
{ 
    { "string", typeof(string) }, 
    { "int", typeof(int) }, 
    // etc 
}; 

一旦你得到了Type你可以得到全名,装配等

下面是一些示例代码,考虑到可空类型:

public static Type FromCSharpAlias(string alias) 
{ 
    bool nullable = alias.EndsWith("?"); 
    if (nullable) 
    { 
     alias = alias.Substring(0, alias.Length - 1); 
    } 
    Type type; 
    if (!CSharpAliasToType.TryGetValue(alias, out type)) 
    { 
     throw new ArgumentException("No such type"); 
    } 
    return nullable ? typeof(Nullable<>).MakeGenericType(new Type[]{ type }) 
        : type; 
} 
+0

到目前为止,我用字典进行映射是一项很重要的工作,但它很难维护。 此外,我想自动查找可空类型: “布尔?” - > System.Nullable'1 [System.Boolean] – Pragmateek 2009-09-22 13:09:39

+0

它以何种方式“沉重”或难以维护?没有必要进行任何维护,除非C#团队添加了新的别名,我认为这不太可能。 (我不会在C#4中包含'dynamic',因为这不构成真正的CLR类型。)至于“?“ - 只要检查字符串是否以它结尾...(将提供示例代码。) – 2009-09-22 13:39:09

1

不要这么复杂。

尝试

typeof(bool).ToString() 
typeof(string).ToString() 
typeof(int).ToString() 
typeof(char).ToString() 

...

相关问题