簡體   English   中英

如何在C#中迭代內置類型?

[英]How to iterate through the built-in types in 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<Type> 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等),並隨着應用過濾器。

沒有內置的方法可以做到這一點; 你可以試試:

foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... })
{
    //...
}

當然,如果您要做很​​多事情,請將數組static readonly並將其放入static readonly變量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM