c# - 为什么 Nullable<T> 被 PropertyInfo.SetValue 特殊对待

标签 c# reflection type-conversion

在实现类似于 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/

相关文章:

c# - 如何发现 USB 存储设备和可写 CD/DVD 驱动器 (C#)

c# - 无法转换 System.Runtime.Remoting.ObjectHandle

c# - 将此 SQL 语句转换为 LINQ

c - 整体提升/转换:为什么我要关心结果类型的名称?

c# - 如何在输出到html之前停止asp.net编码字符?

java - 反射 API 中的原始类型

java - 打印 java 类中所有字段值的最佳方法是什么

c# - .NET Standard 1.x 的 Type.GetInterfaces() 解决方法

string - 如何将uint64转换为字符串

c# - 获取 SPFieldCurrency 字段的数值