Is there a function to check if an object is a builtin data type?

前端 未结 3 1988
日久生厌
日久生厌 2020-12-10 18:58

I would like to see if an object is a builtin data type in C#

I don\'t want to check against all of them if possible.
That is, I don\'t want to do this:

3条回答
  •  时光说笑
    2020-12-10 19:36

    Well, one easy way is to just explicitly list them in a set, e.g.

    static readonly HashSet BuiltInTypes = new HashSet
        (typeof(object), typeof(string), typeof(int) ... };
    
    ...
    
    
    if (BuiltInTypes.Contains(typeOfFoo))
    {
        ...
    }
    

    I have to ask why it's important though - I can understand how it might make a difference if it's a .NET primitive type, but could you explain why you would want your application to behave differently if it's one of the ones for C# itself? Is this for a development tool?

    Depending on the answer to that question, you might want to consider the situation with dynamic in C# 4 - which isn't a type at execution time as such, but is System.Object + an attribute when applied to a method parameter etc.

提交回复
热议问题