使用反射获取 属性 类型

Getting property type with reflection

我通过反射获取 属性 的类型时遇到了一点问题。

我有一个 class,它只包含简单的类型,如字符串、整数、小数...

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 来确定哪个是 stringdecimal。像这样尝试;

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