[英]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.