【问题标题】:How do I loop through my class properties and get their types?如何遍历我的类属性并获取它们的类型?
【发布时间】:2012-06-11 23:30:59
【问题描述】:

我想遍历我的类的属性并获取每个属性类型。我大部分都得到了它,但是当尝试获取类型时,我得到了类型反射,而不是获取字符串、int 等。有任何想法吗?让我知道是否需要更多背景信息。谢谢!

using System.Reflection;

Type oClassType = this.GetType(); //I'm calling this inside the class
PropertyInfo[] oClassProperties = oClassType.GetProperties();

foreach (PropertyInfo prop in oClassProperties)  //Loop thru properties works fine
{
    if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(int))
        //should be integer type but prop.GetType() returns System.Reflection
    else if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(string))
        //should be string type but prop.GetType() returns System.Reflection
    .
    .
    .
 }

【问题讨论】:

    标签: c# class reflection properties


    【解决方案1】:

    首先,你不能在这里使用prop.GetType()——这是PropertyInfo的类型——你的意思是prop.PropertyType

    其次,试试:

    var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
    

    无论它是否可以为空不可为空,这都可以工作,因为如果不是Nullable<T>,GetUnderlyingType 将返回null

    然后,在那之后:

    if(type == typeof(int)) {...}
    else if(type == typeof(string)) {...}
    

    或替代:

    switch(Type.GetTypeCode(type)) {
        case TypeCode.Int32: /* ... */ break;
        case TypeCode.String: /* ... */ break;
        ...
    }
    

    【讨论】:

    • 如果 PropertyType 实际是通过反射访问的,是否还需要使用 Nullable.GetUnderlyingType?
    【解决方案2】:
    【解决方案3】:

    你快到了。 PropertyInfo 类有一个属性PropertyType,它返回属性的类型。当您在 PropertyInfo 实例上调用 GetType() 时,您实际上只是得到了 RuntimePropertyInfo,这是您正在反映的成员的类型。

    因此,要获取所有成员属性的类型,您只需执行以下操作: oClassType.GetProperties().Select(p => p.PropertyType)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多