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