通过反射获取属性的类型我有一点问题。
我有一个类,只包括字符串,int,十进制等简单类型...
public class simple
{
public string article { get; set; }
public decimal price { get; set; }
}
现在我需要通过反射来获取这些属性并按其类型处理它们。
我需要这样的东西:
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;
}
对于字符串,它可以将propInfo.PropertyType.UnderlyingSystemType
用作GetPropType(),但不能用于十进制。
对于十进制作品propInfo.PropertyType.GenericTypeArguments.FirstOrDefault();
但不是字符串。
如何获得所有简单类型的类型?
非常感谢你。怒江
您可以使用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");
}