c# - 我如何遍历我的类属性并获取它们的类型?

标签 c# class reflection properties

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

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
    .
    .
    .
 }

最佳答案

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

其次,尝试:

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

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

然后,在那之后:

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

或替代:

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

关于c# - 我如何遍历我的类属性并获取它们的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939814/

相关文章:

c# - 插件集成的最佳模型

c# - 为什么我不能使用 FindName() 按名称访问文本框?

c# - 确定派生自哪个泛型类型对象

c# - C的反射类特征

java - 将方法名称作为字符串给出时,如何调用 Java 方法?

c# - 在异步/等待方面,常规 foreach 和 ForEach LINQ 运算符有什么区别

c# - 将引用 C++/CLI 包装器的 UserControl 添加到表单的非托管 dll 时出现问题

java - 在类中找不到主要方法/表达式的非法开头

c# - 特性是否保值

c++ - 终止管家是什么意思?