为什么只读变量“someValue”(但我们仍然可以通过反射更改其值)输出为“10”,尽管它实际上确实更改为 55?
static class Program
{
static readonly int someValue = 10;
static void Main(string[] args)
{
Console.WriteLine(someValue); // 10
typeof(Program)
.GetField("someValue", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, 55); // change readonly field via reflection to 55
Console.WriteLine(someValue); // output in console 10,
// but in visual studio debugger it shows 55
Console.ReadKey();
}
}
可能只是 JIT 优化,以防止多次读取变量。
您正在更改已声明为只读的内存位置,因此如果读者缓存了这些值,请不要感到惊讶。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)