【发布时间】:2015-08-31 21:32:36
【问题描述】:
在实现类似于Nullable<T> 的结构时,我发现PropertyInfo.SetValue 对待Nullable 类型的方式与其他类型不同。
对于 Nullable 属性,它可以设置底层类型的值
foo.GetType().GetProperty("NullableBool").SetValue(foo, true);
但对于自定义类型,它会抛出
System.ArgumentException:“SomeType”类型的对象无法转换为 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> 类型通过?
【问题讨论】:
标签: c# reflection type-conversion