Home >Backend Development >C++ >Can Reflection Bypass C#'s Private Readonly Field Restrictions?
Use C# reflection to modify private read-only fields
Theprivate readonly
modifier in C# is designed to prevent fields from being modified after the constructor, but we can explore the possibility of modification through reflection.
Problem: Using reflection to modify private read-only fields
Can private read-only fields be changed using reflection after the constructor has executed?
Detailed analysis
Consider the following C# code:
<code class="language-csharp">public class Foo { private readonly int bar; public Foo(int num) { bar = num; } public int GetBar() { return bar; } } Foo foo = new Foo(123); Console.WriteLine(foo.GetBar()); // 输出 123 // 在此处添加反射代码。 Console.WriteLine(foo.GetBar()); // 输出 456</code>
Solution using reflection
Reflection provides a way to achieve this goal. Here’s how:
<code class="language-csharp">typeof(Foo).GetField("bar", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(foo, 567);</code>
This code uses reflection to modify the private read-only field "bar" of the Foo
class instancefoo
. Although readonly
prevents direct modification, reflection bypasses this limitation. It should be noted that this approach is generally not recommended because it breaks encapsulation and may make the code difficult to maintain and debug.
The above is the detailed content of Can Reflection Bypass C#'s Private Readonly Field Restrictions?. For more information, please follow other related articles on the PHP Chinese website!