在实现类似于 Nullable<T>
的结构时我发现 PropertyInfo.SetValue
对待 Nullable
键入与其他人不同。
对于 Nullable 属性,它可以设置基础类型的值
foo.GetType().GetProperty("NullableBool").SetValue(foo, true);
但是对于自定义类型它会抛出
System.ArgumentException: Object of type 'SomeType' cannot be converted to type NullableCase.CopyOfNullable 1[SomeType]
即使所有转换运算符都以与原始 Nullable<T>
相同的方式被覆盖
重现代码:
using System;
namespace NullableCase
{
/// <summary>
/// Copy of Nullable from .Net source code
/// without unrelated methodts for brevity
/// </summary>
public struct CopyOfNullable<T> where T : struct
{
private bool hasValue;
internal T value;
public CopyOfNullable(T value)
{
this.value = value;
this.hasValue = true;
}
public bool HasValue
{
get
{
return hasValue;
}
}
public T Value
{
get
{
if (!hasValue)
{
throw new InvalidOperationException();
}
return value;
}
}
public static implicit operator CopyOfNullable<T>(T value)
{
return new CopyOfNullable<T>(value);
}
public static explicit operator T(CopyOfNullable<T> value)
{
return value.Value;
}
}
class Foo
{
public Nullable<bool> NullableBool { get; set; }
public CopyOfNullable<bool> CopyOfNullablBool { get; set; }
}
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
foo.GetType().GetProperty("NullableBool").SetValue(foo, true);
foo.GetType().GetProperty("CopyOfNullablBool").SetValue(foo, true); //here we get ArgumentException
}
}
}
为什么 PropertyInfo.SetValue
CopyOfNullable
失败输入并通过 Nullable<T>
?
最佳答案
Nullable<T>
在 CLR 类型系统中有特殊支持自动从 T
转换.
事实上,不可能有Nullable<T>
的盒装实例;可空值框到基础值或实际空值。
这是 BCL 中为数不多的魔法类型之一;无法复制。
关于c# - 为什么 Nullable<T> 被 PropertyInfo.SetValue 特殊对待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32320324/