如何遍历我的类属性并获取其类型?

Cur*_*tis 2 c# reflection properties class

我想遍历我的类的属性并获取每个属性类型.我大部分时间都得到了它,但是在尝试获取类型时,而不是获取字符串,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
    .
    .
    .
 }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 13

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

其次,尝试:

var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
Run Code Online (Sandbox Code Playgroud)

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

然后,在那之后:

if(type == typeof(int)) {...}
else if(type == typeof(string)) {...}
Run Code Online (Sandbox Code Playgroud)

或替代方案:

switch(Type.GetTypeCode(type)) {
    case TypeCode.Int32: /* ... */ break;
    case TypeCode.String: /* ... */ break;
    ...
}
Run Code Online (Sandbox Code Playgroud)