2012-04-26 94 views
4

可能重複:
How can I get the primitive name of a type in C#?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); 
     } 

該代碼輸出:

布爾,字節,字符,雙,Int16的,的Int32,Int64的,IntPtr的,爲SByte, 單,UINT16,UInt32的,UINT64,UIntPtr,

我想通過bool通過byte和更換BooleanByte所以在可能的時候,不依賴於固定的數組或字典。有沒有辦法做到這一點?

回答

6

這是一個重複,以

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

這是飛碟雙向一個很好的答案,也

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 
+0

它像一個魅力。謝謝。 – 2012-04-26 17:39:00