小编典典

如何测试类型是否为原始

c#

我有一段代码将类型序列化为Html标签。

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

这个伟大的工程,但我希望它只是对基本类型,像这样做intdoublebool等,以及其他类型的不是原始的,但可以像容易序列化string。我希望它忽略其他所有内容,例如列表和其他自定义类型。

谁能建议我该怎么做?还是我需要在某个地方指定要允许的类型,然后打开属性的类型以查看是否允许?有点乱,所以如果我有一个比较整洁的方法,那会很好。


阅读 241

收藏
2020-05-19

共1个答案

小编典典

您可以使用该属性Type.IsPrimitive,但要小心,因为我们可以认为有些类型是基本类型,但不是,例如DecimalString

编辑1: 添加了示例代码

这是一个示例代码:

if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
    // Is Primitive, or Decimal, or String
}

编辑2:
作为@SLaks注释,也许您也想将其他类型视为原语。我认为您必须将这些变化
一个接一个 地添加。

编辑3: IsPrimitive
=(布尔值,字节,SByte,Int16,UInt16,Int32,UInt32,Int64,UInt64,IntPtr,UIntPtr,Char,Double和Single),要检查的花药基本类型(t
== typeof(DateTime ))

2020-05-19