簡體   English   中英

在不同的 class 和文件中定義私有浮點數的值

[英]Defining the value of a private float in a different class and file


public class LevelLighting
{
    public static float nightvisionFogIntensity;

    private static float auroraBorealisCurrentIntensity;
}

C#

這是我自己引用的代碼中 class 的一小部分,我想更改和實現的值是 auroraBorealisCurrentIntensity,但它是私有的,所以它告訴我 class 中沒有它的定義。是否有即使它被設置為私有,我也可以通過任何方式使用它?

我無法編輯上面的代碼,只有我自己的代碼需要引用上面的代碼。

LevelLightning.nightvisionFogIntensity = 1f;

這有效,因為 nightvisionFogIntensity 是公開的

LevelLighting.auroraBorealisCurrentIntensity = 1f;

這不起作用,因為 auroraBorealisCurrentIntensity 是私有的。

謝謝你的幫助。

首先,我需要警告您,更改不應該更改的私有字段是危險的,並且可能導致目標 object 出現意外行為。

也就是說,如果您仍然想這樣做,我認為唯一的方法就是使用反射 我准備了一個小例子。 這是您的 class 的一個版本,它有一個方法PrintBorealisValue()來幫助我們顯示更改后的結果:

public class LevelLightening
{
    public static float nightvisionFogIntensity;

    private static float auroraBorealisCurrentIntensity;

    public static void PrintBorealisValue()
    {
            Console.WriteLine(auroraBorealisCurrentIntensity);
    }
}

現在讓我們實例化這個 class 的 object 並更改它的私有變量:

LevelLightening.PrintBorealisValue(); // prints "0"

var borealisField = typeof(LevelLightening)
                            .GetField("auroraBorealisCurrentIntensity", BindingFlags.NonPublic | BindingFlags.Static);
// will be a good idea to check "borealisField" for null here
borealisField.SetValue(null, 3.14f); 

LevelLightening.PrintBorealisValue(); // prints "3.14"

同樣值得注意的是,使用反射通常比不使用反射做同樣的事情要慢(這是顯而易見的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM