是否有一个函数可以检查对象是否是内置数据类型?
我想查看一个对象是否是内置数据类型 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不直接,但您可以执行以下简化检查
IsPrimitive 检查将捕获除字符串、对象和小数之外的所有内容。
编辑
虽然这种方法有效,但我更喜欢乔恩的解决方案。 原因很简单,检查我必须对解决方案进行的编辑次数,因为我忘记的类型是或不是基元。 将它们全部明确地列在一个集合中会更容易。
Not directly but you can do the following simplified check
The IsPrimitive check will catch everything but string, object and decimal.
EDIT
While this method works, I would prefer Jon's solution. The reason is simple, check the number of edits I had to make to my solution because of the types I forgot were or were not primitives. Easier to just list them all out explicitly in a set.
好吧,一个简单的方法是直接将它们明确地列出在一个集合中,例如,
我必须问为什么它很重要 - 我可以理解如果它是一个 .NET 原始类型,但是您能否解释一下为什么您希望您的应用程序表现不同(如果它是其中之一)对于 C# 本身? 这是开发工具吗?
根据该问题的答案,您可能需要考虑 C# 4 中
dynamic
的情况 - 它不是执行时的类型,而是System.Object
code> + 应用于方法参数等时的属性。Well, one easy way is to just explicitly list them in a set, e.g.
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 isSystem.Object
+ an attribute when applied to a method parameter etc.我认为这是最好的可能性之一:
I think this is one of the best possibilies: