我使用反射来获取匿名类型的值:
object value = property.GetValue(item, null);
Run Code Online (Sandbox Code Playgroud)
当底层值是可空类型(T?)时,如何在值为null时获取基础类型?
特定
int? i = null;
type = FunctionX(i);
type == typeof(int); // true
Run Code Online (Sandbox Code Playgroud)
寻找FunctionX().希望这是有道理的.谢谢.
你可以这样做:
if(type.IsgenericType)
{
Type genericType = type.GetGenericArguments()[0];
}
Run Code Online (Sandbox Code Playgroud)
编辑:用于一般用途:
public Type GetTypeOrUnderlyingType(object o)
{
Type type = o.GetType();
if(!type.IsGenericType){return type;}
return type.GetGenericArguments()[0];
}
Run Code Online (Sandbox Code Playgroud)
用法:
int? i = null;
type = GetTypeOrUnderlyingType(i);
type == typeof(int); //true
Run Code Online (Sandbox Code Playgroud)
这适用于任何泛型类型,而不仅仅是Nullable.
| 归档时间: |
|
| 查看次数: |
3844 次 |
| 最近记录: |