我正在使用反射从匿名类型中获取值:
object value = property.GetValue(item, null);
当底层值为可空类型(T?)时,当值为空时如何获取底层类型?
给定
int? i = null;
type = FunctionX(i);
type == typeof(int); // true
正在寻找 FunctionX()。希望这是有道理的。谢谢。
最佳答案
你可以这样做:
if(type.IsgenericType)
{
Type genericType = type.GetGenericArguments()[0];
}
编辑: 对于一般用途:
public Type GetTypeOrUnderlyingType(object o)
{
Type type = o.GetType();
if(!type.IsGenericType){return type;}
return type.GetGenericArguments()[0];
}
用法:
int? i = null;
type = GetTypeOrUnderlyingType(i);
type == typeof(int); //true
这适用于任何泛型,而不仅仅是 Nullable。
关于C# 反射属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/802981/