问题描述
刚玩c#的时候,发现一件很奇怪的事情.
While just playing with c#, realized a strange thing.
代码如下:
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.Write(string.Empty);
typeof(string)
.GetField("Empty", BindingFlags.Static | BindingFlags.Public)
.SetValue(null, "Tolgahan");
Console.WriteLine(string.Empty);
// output : Tolgahan
}
}
为什么反射让我们改变只读字段?
Why reflection let us to change readonly fields?
问题是为什么允许通过反射进行设置",而不是怎么做",所以它不是 我可以使用反射在 C# 中更改私有只读字段吗?.
The question is "why the setting via reflection is allowed", not "how to do it", so it is not a duplicate of Can I change a private readonly field in C# using reflection?.
推荐答案
同样,化学定律说没有反应可以使一种元素的原子变成另一种元素的原子,但物理定律说它一直发生.化学是物理学的一个受限子集,目的是将问题简化为更易于解决的方式.
In the same way the laws of chemistry say that no reaction can cause an atom of one element to change into an atom of another element, but the laws of physics say it happens all the time. Chemistry is a restricted subset of physics in order to simplify problems into a more solvable manner.
在这种情况下,反射是物理,而正常编程是化学.它以更简单的思维方式运作.反射使您可以规避那组更简单的规则,让您接触新的流程,但也有新的危险.
Reflection is the physics in this case, where normal programming is the chemistry. It operates in a simpler mindset. Reflection allows you to circumvent that simpler set of rules, exposing you to new processes, but also new dangers.
这篇关于设置只读字段(这是错误吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!