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

mus*_*bar 8 reflection struct properties c#-4.0

   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();
    }
Run Code Online (Sandbox Code Playgroud)

打印的第一个值是32,而第二个值是0.没有异常抛出

jbt*_*ule 12

这是因为装箱你的结构会复制它,所以你应该先装箱,这样你就可以从你修改过的相同数据中调用它.以下代码有效:

    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();
Run Code Online (Sandbox Code Playgroud)


Bot*_*000 5

struct 是 ValueType,按值传递,这意味着您只能传递整个结构的副本,而不是对原始对象的引用。

因此,当您将其传递给时,会将info.SetValue(_priceStruct, 32, null)一个副本传递给该方法并进行变异,因此根本不会更改原始对象。可变结构是邪恶的另一个原因。