繁体   English   中英

在 C# 中设置只读属性的值

[英]Setting the value of a read only property in C#

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

一般来说,没有。

三个例子:

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

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

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

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

尝试这个:

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

您可以在这两种情况下:

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

是的,这是绝对可能的。 我不知道这是好的做法还是对您的目的有帮助。 听从@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;
        }
    }
}

正如马克所说,在某些情况下你不能像 . 认为属性本身可以是从其他属性、成员派生的函数。

但是,您可能想尝试此处解释的机制:

是否可以通过反射设置私有属性?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM