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

前端 未结 3 1565
忘掉有多难
忘掉有多难 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:39

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

    You might want something like:

    public static IEnumerable 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.

提交回复
热议问题