Using Reflection to Access Private Class Members
Problem:
Is it possible to use Reflection to access a class's private fields, for example, the _bar
field in the code below?
<code class="language-csharp">class Foo { [SomeAttribute] private string _bar; public string BigBar { get { return this._bar; } } }</code>
Solution:
Yes, Reflection allows access to private fields. Here's how to retrieve private fields using BindingFlags
:
<code class="language-csharp">FieldInfo[] fields = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);</code>
BindingFlags.NonPublic
includes non-public members (like private fields), and BindingFlags.Instance
ensures only instance fields are returned. The fields
array will then contain the private _bar
field.
The above is the detailed content of Can Reflection Access Private Class Fields?. For more information, please follow other related articles on the PHP Chinese website!