【问题标题】:Setting the value of a read only property in C#在 C# 中设置只读属性的值
【发布时间】:2016-02-14 06:42:12
【问题描述】:

我正在尝试用 c# 为游戏制作一个 mod,我想知道是否有办法使用反射来更改只读属性的值。

【问题讨论】:

标签: c# reflection


【解决方案1】:

一般来说不会。

三个例子:

public int Value { get { return _value + 3; } } // No

public int Value { get { return 3; } } // No

public int Value { get; private set; } // Yes

因此,当该属性具有相应的私有、受保护或内部字段时,您可以更改该属性的值。

【讨论】:

    【解决方案2】:

    正如 Mark 所说,在某些情况下您可能无法使用 .认为属性本身可能是从其他属性、成员派生的函数。

    但是,您可能想尝试这里解释的机制:

    Is it possible to set private property via reflection?

    【讨论】:

      【解决方案3】:

      试试这个:

      typeof(foo).GetField("bar", BindingFlags.Instance|BindingFlags.NonPublic).SetValue(foo,yourValue)
      

      【讨论】:

        【解决方案4】:

        是的,这是绝对可能的。我不知道这是好的做法还是对您的目的有帮助。离开@ske57 的好建议,这里是一个演示反射的示例程序。将初始字段值 5 和反射字段值 75 写入控制台。

        using System;
        using System.Reflection;
        
        namespace JazzyNamespace
        {
            class Program
            {
                static void Main()
                {
                    var reflectionExample = new ReflectionExample();
                    // access the compiled value of our field
                    var initialValue = reflectionExample.fieldToTest;
        
                    // use reflection to access the readonly field
                    var field = typeof(ReflectionExample).GetField("fieldToTest", BindingFlags.Public | BindingFlags.Instance);
        
                    // set the field to a new value during
                    field.SetValue(reflectionExample, 75);
                    var reflectedValue = reflectionExample.fieldToTest;
        
                    // demonstrate the change
                    Console.WriteLine("The complied value is {0}", initialValue);
                    Console.WriteLine("The value changed is {0}", reflectedValue);
                    Console.ReadLine();
                }
        
            }
        
            class ReflectionExample
            {
                public readonly int fieldToTest;
        
                public ReflectionExample()
                {
                    fieldToTest = 5;
                }
            }
        }
        

        【讨论】:

          【解决方案5】:

          你可以在这两种情况下:

          readonly int value = 4;
          

          int value {get; private set}
          

          使用

          typeof(Foo)
             .GetField("value", BindingFlags.Instance)
             .SetValue(foo, 1000); // (the_object_you_want_to_modify, the_value_you_want_to_assign_to_it)
          

          你不能修改

          int value { get { return 4; } }
          

          虽然。

          如果它返回一个计算值,例如

          int value { get { return _private_val + 10; } }
          

          您必须相应地修改_private_val

          【讨论】: