Den*_*sky 5 c# reflection type-conversion
实现类似于Nullable<T>我的结构时,发现PropertyInfo.SetValue对待Nullable类型与其他类型不同.对于Nullable属性,它可以设置基础类型的值
foo.GetType().GetProperty("NullableBool").SetValue(foo, true);
Run Code Online (Sandbox Code Playgroud)
但对于自定义类型,它会抛出
System.ArgumentException:类型为'SomeType'的对象无法转换为NullableCase.CopyOfNullable类型[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
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么类型和传递PropertyInfo.SetValue失败?CopyOfNullableNullable<T>
SLa*_*aks 10
Nullable<T>在CLR类型系统内有特殊支持自动转换T.
事实上,不可能有一个盒装实例Nullable<T>; 可空值可以选择底层值或实际空值.
这是BCL中为数不多的神奇类型之一; 复制是不可能的.
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |