reflection - 为什么反射不在Struct中设置属性?

标签 reflection c#-4.0 struct properties

   class PriceClass {

        private int value;
        public int Value
        {
            get { return this.value; }
            set { this.value = value; }
        }           
    }


    struct PriceStruct
    {

        private int value;
        public int Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    }
    static void Main(string[] args)
    {
        PriceClass _priceClass = new PriceClass();
        Type type = typeof(PriceClass);
        PropertyInfo info = type.GetProperty("Value");
        info.SetValue(_priceClass, 32, null);
        Console.WriteLine(_priceClass.Value);

        PriceStruct _priceStruct = new PriceStruct();
        type = typeof(PriceStruct);
        info = type.GetProperty("Value");
        info.SetValue(_priceStruct, 32, null);
        Console.WriteLine(_priceStruct.Value);

        Debugger.Break();
    }

打印的第一个值是32,第二个值是0。不会引发异常

最佳答案

这是因为对结构进行装箱会对其进行复制,因此您应该更早对它进行装箱,以便从修改后的相同数据中调用 setter/getter 。以下代码有效:

    object _priceStruct = new PriceStruct(); //Box first
    type = typeof(PriceStruct);
    info = type.GetProperty("Value");
    info.SetValue(_priceStruct, 32, null);
    Console.WriteLine(((PriceStruct)_priceStruct).Value); //now unbox and get value

    Debugger.Break();

关于reflection - 为什么反射不在Struct中设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6608368/

相关文章:

java - 在最终公共(public)类Java中修改最终静态变量

c# - 获取实现特定开放通用类型的所有类型

java - 如何从字符串创建 Java 内置对象

c#-4.0 - 通过将所需类型作为参数传递来将字符串值转换为特定类型

c++ - 结构比较器访问 C++ 中的另一个字段

c - 如何使一个字段指向它的结构?

Java 反射 : how to get field value from an object, 不知道它的类

asp.net-mvc-3 - Dapper 使用存储过程 (MSSQL) 时的缓存解决方案

c# - 针对 ActiveDirectory 进行身份验证

c - 在 C 中释放结构的函数