Home >Backend Development >C++ >Can Reflection Modify Private Readonly Fields in C#?
Use C# reflection to modify private read-only fields
Reflection technology in C# is powerful, allowing access and manipulation of runtime information on types, methods, properties, and fields. A common question is: Can private read-only fields be modified after the object is constructed?
Consider the following scenario:
<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</code>
Here, the bar
field is declared as private readonly
, which means it can only be assigned in the constructor. To change its value later, you need to use reflection.
Using reflection, we can access private fields by specifying the field name and binding flag. Here’s how:
<code class="language-csharp">typeof(Foo).GetField("bar", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(foo, 456);</code>
The above statement uses the GetField
method to get the bar
field, and then uses the SetValue
method to change its value to 456.
After executing the reflection code, calling foo.GetBar()
will output 456, proving that the private read-only field was successfully modified at runtime. However, it is important to note that modifying read-only fields in this manner is not recommended for production code as it may cause unexpected behavior or runtime errors.
The above is the detailed content of Can Reflection Modify Private Readonly Fields in C#?. For more information, please follow other related articles on the PHP Chinese website!