我试图在使用大量反射的环境中创建扩展方法。
方法的目的是重新创建 default() 在运行时所做的事情。
除了那些 Nullable<> 类型之外,它对所有东西都适用。即使是 ?-Types 也能正常工作。
我不知道如何找出分配给对象变量的值是否为 Nullable<> 而不是“常规值类型”
在这种情况下,Nullable.GetUnderlyingType 方法返回 null,但适用于 ?-Type。
我们知道 default(Nullable) == null。 当 Nullable 被赋值为 0 时,我的扩展方法会产生错误的结果,因为 0 == default(int)。
我希望您明白我在这里试图解释的内容,简而言之: - 如何确定“随机”对象是 Nullable 而不是 int?
该方法看起来像这样(为简单起见删除了所有缓存) 我从这里拿了零件How to check if an object is nullable?
public static bool IsDefault(this object obj)
{
if(obj == null)
return true;
else
{
Type objType = obj.GetType(); // This gives int32 for Nullabe<int> !?!
if(Nullable.GetUnderlyingType(objType) != null)
return false;
else if(objType.IsValueType)
return Object.Equals(obj, Activator.CreateInstance(objType);
else
return false;
}
}
为了更清楚我不能使用通用的东西...
最佳答案
您不能这样做,因为当您调用该方法时,可空结构被装箱为 object
,并变为 null
或 Int32
值。这在较早的答案中有解释:Why GetType returns System.Int32 instead of Nullable<Int32>?
如果您的变量在调用此方法的地方被键入为对象,我认为您无法获得所需的信息 - 它已经被装箱了。
关于c# - 可为空,检查默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453907/