问题描述
我有一个序列化类型成HTML标记code块。
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
,双击
, 布尔
等,以及其他类型不属于原始的,但可以像字符串
容易序列化。我希望它忽略一切就像列表和放大器;其他自定义类型。
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
,但要小心,因为有一些类型,我们可以认为是原语,但他们地图无法,例如小数
和字符串
。
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: 添加样品code 的
下面是一个简单的code:
Here is a sample code:
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
// Is Primitive, or Decimal, or String
}
编辑2: @SLaks 的意见,有一些也许你想其他类型对待基元,太。我认为you'll要添加这个变化的一一的
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 =(布尔,字节,为SByte,Int16的,UINT16,的Int32,UInt32的,Int64的,UINT64,IntPtr的,UIntPtr,煤焦,双和单)
花药原始样型检查(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))
这篇关于如何测试如果类型是基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!