5

我想看看一个对象是否是C#中的内置数据类型

如果可能的话,我不想检查所有这些。
也就是说,我不想这样做:

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

更新

我正在尝试递归地创建一个 PropertyDescriptorCollection,其中 PropertyDescriptor 类型可能不是内置值。所以我想做这样的事情(注意:这还不行,但我正在努力):

    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);
    }
4

3 回答 3

9

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

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 检查将捕获除字符串、对象和小数之外的所有内容。

编辑

虽然这种方法有效,但我更喜欢 Jon 的解决方案。原因很简单,检查我必须对我的解决方案进行的编辑次数,因为我忘记的类型是或不是原语。更容易在一组中明确列出它们。

于 2009-07-11T22:25:25.387 回答
5

好吧,一种简单的方法是在一个集合中明确列出它们,例如

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

...


if (BuiltInTypes.Contains(typeOfFoo))
{
    ...
}

我不得不问为什么它很重要 - 我可以理解如果它是一个.NET 原始类型它可能会产生什么影响,但是如果它是 C# 本身的应用程序之一,你能解释一下为什么你希望你的应用程序表现不同吗?这是开发工具吗?

根据该问题的答案,您可能需要考虑dynamicC# 4 中的情况 - 这不是执行时的类型,而是System.Object+ 应用于方法参数等时的属性。

于 2009-07-11T22:26:15.603 回答
1

我认为这是最好的可能性之一:

private static bool IsBulitinType(Type type)
{
    return (type == typeof(object) || Type.GetTypeCode(type) != TypeCode.Object);
}
于 2013-06-10T08:43:52.757 回答