我在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
等等,如果可能的话,不依赖于固定数组或字典。有没有办法做到这一点?
答案 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