How to iterate through the built-in types in C#?

前端 未结 3 1514
忘掉有多难
忘掉有多难 2021-02-06 01:41

I want to iterate through the built-in types (bool, char, sbyte, byte, short, ushort, etc) in c#.

How to do that?

foreach(var x in GetBuiltInTypes())
{
/         


        
相关标签:
3条回答
  • 2021-02-06 02:19

    There's no built-in way to do that; you can try:

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

    Of course, if you're going to be doing this a lot, factor out the array and put it inside a static readonly variable.

    0 讨论(0)
  • 2021-02-06 02:36

    System.TypeCode is the closest thing I can think of.

    foreach(TypeCode t in Enum.GetValues(typeof(TypeCode)))
    { 
        // do something interesting with the value...
    }
    
    0 讨论(0)
  • 2021-02-06 02:39

    It depends on how you define "built-in" types of course.

    You might want something like:

    public static IEnumerable<Type> GetBuiltInTypes()
    {
       return typeof(int).Assembly
                         .GetTypes()
                         .Where(t => t.IsPrimitive);
    }
    

    This should give you (from MSDN):

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

    If you have a different definition, you might want to enumerate all of the types in common BCL assemblies (such as mscorlib, System.dll, System.Core.dll etc.), applying your filter as you go along.

    0 讨论(0)
提交回复
热议问题