Nun*_*zio 4 c# reflection gettype
我通过反射获取属性的类型时遇到了一个小问题。
我有一个类,仅包含简单类型,如字符串、整数、小数......
public class simple
{
public string article { get; set; }
public decimal price { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我需要通过反射获取这些属性并按其类型处理它们。
我需要这样的东西:
Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
Type propType = ?? *GetPropType*() ??
switch (Type.GetTypeCode(propType))
{
case TypeCode.Decimal:
doSome1;
break;
case TypeCode.String:
doSome2;
break;
}
Run Code Online (Sandbox Code Playgroud)
对于字符串,它可以像 GetPropType() 一样工作
propInfo.PropertyType.UnderlyingSystemType
,但对于十进制则不然。
对于十进制有效propInfo.PropertyType.GenericTypeArguments.FirstOrDefault();
,但不适用于字符串。
Hos可以获取所有简单类型的类型吗?
您可以使用PropertyType
来确定哪个是string
或decimal
。尝试这样;
Type t = obj.GetType();
PropertyInfo propInfo = t.GetProperty("article");
if (propInfo.PropertyType == typeof(string))
{
Console.WriteLine("String Type");
}
if (propInfo.PropertyType == typeof(decimal)
|| propInfo.PropertyType == typeof(decimal?))
{
Console.WriteLine("Decimal Type");
}
Run Code Online (Sandbox Code Playgroud)