简体   繁体   中英

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


public class LevelLighting
{
    public static float nightvisionFogIntensity;

    private static float auroraBorealisCurrentIntensity;
}

In C#

This is a small bit of the class in a code I'm referencing for my own, the value i want to change and implement is auroraBorealisCurrentIntensity, but it is private so it tells me there is no definition for it in the class. Is there any way I can use this value even though it is set as private?

I'm not able to edit the code above, only my own code that needs to reference the code above.

LevelLightning.nightvisionFogIntensity = 1f;

This works, since nightvisionFogIntensity is public

LevelLighting.auroraBorealisCurrentIntensity = 1f;

This doesn't work, since auroraBorealisCurrentIntensity is private.

Thanks for any help.

First and foremost I need to warn you that changing private fields that are not supposed to be changed is dangerous and can lead to unexpected behavior of the target object.

That said if you still want to do it the only way I see it is using reflection . I prepared a little example. Here is a version of your class that has a method PrintBorealisValue() to help us show the result after the change:

public class LevelLightening
{
    public static float nightvisionFogIntensity;

    private static float auroraBorealisCurrentIntensity;

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

Now let's instantiate an object of this class and change it's private variable:

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"

It is also worth noting that using reflection is usually slower than doing the same thing without reflection (which is kind of obvious).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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