簡體   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