C#,反射和原始类型

时间:2012-04-26 17:19:45

标签: c# reflection primitive-types

  

可能重复:
  How can I get the primitive name of a type in C#?

我在C#中有以下代码:

        Assembly sysAssembly = 0.GetType().Assembly;
        Type[] sysTypes = sysAssembly.GetTypes();
        foreach (Type sysType in sysTypes)
        {
            if (sysType.IsPrimitive && sysType.IsPublic)
                Console.WriteLine(sysType.Name);
        }

此代码输出:

  

Boolean,Byte,Char,Double,Int16,Int32,Int64,IntPtr,SByte,   Single,UInt16,UInt32,UInt64,UIntPtr,

我想将Boolean替换为bool,将Byte替换为byte等等,如果可能的话,不依赖于固定数组或字典。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:6)

这与

重复

C# - Get user-friendly name of simple types through reflection?

这也是Skeet的一个很好的答案

How can I get the primitive name of a type in C#?

答案是,你可以,没有字典。

Type t = typeof(bool);

string typeName;
using (var provider = new CSharpCodeProvider())
{
  var typeRef = new CodeTypeReference(t);
  typeName = provider.GetTypeOutput(typeRef);
}

Console.WriteLine(typeName);    // bool