如何在C#中迭代内置类型?
我想在c#中遍历内置类型(bool,char,sbyte,byte,short,ushort等)。
怎么做?
foreach(var x in GetBuiltInTypes()) { //do something on x }
System.TypeCode是我能想到的最接近的东西。
foreach(TypeCode t in Enum.GetValues(typeof(TypeCode))) { // do something interesting with the value... }
这取决于你如何定义“内置”类型的课程。
您可能需要以下内容:
public static IEnumerable GetBuiltInTypes() { return typeof(int).Assembly .GetTypes() .Where(t => t.IsPrimitive); }
这应该给你(来自MSDN ):
Boolean,Byte,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single。
如果您有不同的定义,则可能需要枚举常见BCL程序集中的所有类型(例如mscorlib,System.dll,System.Core.dll等),并在进行过程时应用filter。
没有内置的方法可以做到这一点; 你可以试试:
foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... }) { //... }
当然,如果您要做很多事情,请将数组static readonly
并将其放入static readonly
变量中。