问题描述
我想看看如果对象是href=\"http://msdn.microsoft.com/en-us/library/cs7y5x0x.aspx\" rel=\"nofollow\">内建数据类型
根据这个问题的答案,你可能要考虑在C#4 动态
的情况 - 这是不是在执行时是这样的类型,但为 System.Object的
+当应用于方法参数的属性等。
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:
Object foo = 3;
Type type_of_foo = foo.GetType();
if (type_of_foo == typeof(string))
{
...
}
else if (type_of_foo == typeof(int))
{
...
}
...
Update
I'm trying to recursively create a PropertyDescriptorCollection where the PropertyDescriptor types might not be builtin values. So I wanted to do something like this (note: this doesn't work yet, but I'm working on it):
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);
}
Well, one easy way is to just explicitly list them in a set, e.g.
static readonly HashSet<Type> BuiltInTypes = new HashSet<Type>
(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.
这篇关于是否有检查的对象是一个内置的数据类型的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!