【问题标题】:Getting property type with reflection使用反射获取属性类型
【发布时间】:2018-06-05 19:27:30
【问题描述】:

通过反射获取属性的类型我有一个小问题。

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

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(); 但不适用于字符串。

Hos 可以获取所有简单类型的类型吗?

【问题讨论】:

  • 呃,propInfo.PropertyType 应该足够了。 Fiddle here

标签: c# reflection gettype


【解决方案1】:

您可以使用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");
}

【讨论】:

  • 我不知道为什么,但是我的小数属性的 propInfo.PropertyType 的内容是这样的:propType = {Name = "Nullable1" FullName = "System.Nullable1[[System.Decimal, mscorlib, Version=4.0 .0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"} 这不像 typeof(decimal) ?!为什么?
  • @Nunzio 您的问题代码不正确。你的代码必须有decimal? price,在哪里?真的只是Nullable<decimal> price的语法糖
  • 我猜,您将属性定义为“十进制”?而不是“十进制”。我更新了答案。
  • 哦,好的,现在我明白了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
相关资源
最近更新 更多