代码之家  ›  专栏  ›  技术社区  ›  SwDevMan81

是否有一个函数可以检查对象是否是内置数据类型?

  •  5
  • SwDevMan81  · 技术社区  · 16 年前

    我想看看一个物体是不是 builtin data type 在C#


    不要

            Object foo = 3;
            Type type_of_foo = foo.GetType();
            if (type_of_foo == typeof(string))
            {
                ...
            }
            else if (type_of_foo == typeof(int))
            {
                ...
            }
            ...
    

        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            PropertyDescriptorCollection cols = base.GetProperties(attributes);
    
            List<PropertyDescriptor> list_of_properties_desc = CreatePDList(cols);
            return new PropertyDescriptorCollection(list_of_properties_desc.ToArray());
        }
    
        private List<PropertyDescriptor> CreatePDList(PropertyDescriptorCollection dpCollection)
        {
            List<PropertyDescriptor> list_of_properties_desc = new List<PropertyDescriptor>();
            foreach (PropertyDescriptor pd in dpCollection)
            {
                if (IsBulitin(pd.PropertyType))
                {
                    list_of_properties_desc.Add(pd);
                }
                else
                {
                    list_of_properties_desc.AddRange(CreatePDList(pd.GetChildProperties()));
                }
            }
            return list_of_properties_desc;
        }
    
        // This was the orginal posted answer to my above question
        private bool IsBulitin(Type inType)
        {
            return inType.IsPrimitive || inType == typeof(string) || inType == typeof(object);
        }
    
    3 回复  |  直到 16 年前
        1
  •  9
  •   JaredPar    16 年前

    不直接,但您可以进行以下简化检查

    public bool IsBulitin(object o) {
      var type = o.GetType();
      return (type.IsPrimitive && type != typeof(IntPtr) && type != typeof(UIntPtr))
            || type == typeof(string) 
            || type == typeof(object) 
            || type == typeof(Decimal);
    }
    

    IsPrimitive检查将捕获除字符串、对象和小数之外的所有内容。

        2
  •  5
  •   Jon Skeet    16 年前

    好吧,一种简单的方法是将它们明确地列在一组中,例如。

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

    .NET primitive type ,但是,如果你的应用程序是C#本身的应用程序之一,你能解释一下为什么你希望它的行为不同吗?这是开发工具吗?

    dynamic System.Object +当应用于方法参数等时的属性。

        3
  •  1
  •   k3flo    12 年前

    我认为这是最好的选择之一:

    private static bool IsBulitinType(Type type)
    {
        return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
    }