如何测试类型是否为原始类型 [英] How To Test if Type is Primitive
问题描述
我有一段代码可以将类型序列化为 Html 标记.
I have a block of code that serializes a type into a Html tag.
Type t = typeof(T); // I pass <T> in as a paramter, where myObj is of type T
tagBuilder.Attributes.Add("class", t.Name);
foreach (PropertyInfo prop in t.GetProperties())
{
object propValue = prop.GetValue(myObj, null);
string stringValue = propValue != null ? propValue.ToString() : String.Empty;
tagBuilder.Attributes.Add(prop.Name, stringValue);
}
这很好用,除了我希望它只对原始类型执行此操作,例如 int
、double
、bool
等,以及其他不是原始类型但可以像 string
一样轻松序列化的类型.我希望它忽略其他所有内容,例如 Lists &其他自定义类型.
This works great, except I want it to only do this for primitive types, like int
, double
, bool
etc, and other types that aren't primitive but can be serialized easily like string
. I want it to ignore everything else like Lists & other custom types.
谁能建议我怎么做?或者我是否需要在某处指定我想要允许的类型并打开属性的类型以查看它是否被允许?这有点乱,所以如果我有更整洁的方式就好了.
Can anyone suggest how I do this? Or do I need to specify the types I want to allow somewhere and switch on the property's type to see if it's allowed? That's a little messy, so it'd be nice if I there was a tidier way.
推荐答案
你可以使用属性Type.IsPrimitive
,但是要小心,因为有些类型我们可以认为是原始类型,但是它们不是,例如 Decimal
和 String
.
You can use the property Type.IsPrimitive
, but be carefull because there are some types that we can think that are primitives, but they aren´t, for example Decimal
and String
.
编辑 1:添加示例代码
这是一个示例代码:
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
// Is Primitive, or Decimal, or String
}
编辑 2: 作为 @SLaks 评论,您可能还想要其他类型也将其视为原语.我认为您必须一一添加这些变化.
Edit 2: As @SLaks comments, there are other types that maybe you want to treat as primitives, too. I think that you´ll have to add this variations one by one.
编辑 3: IsPrimitive = (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single),花药 Primitive-Like 类型要检查 (t == typeof(DateTime))
Edit 3: IsPrimitive = (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single), Anther Primitive-Like type to check (t == typeof(DateTime))
这篇关于如何测试类型是否为原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!