Note that there are some explanatory texts on larger screens.

plurals
  1. POReflection in a Windows 8 app
    text
    copied!<p>I'm Unit Testing a class which has 2 private member variables inside of it. I have created a class which inherits from the class I am testing.</p> <p>At first I just made the variables I wanted to access <code>protected</code> but I thought it would be cool if I could keep them private and use reflection to access them. I Googled and found various articles (&amp; questions asked on here (http://stackoverflow.com/questions/4097682/c-sharp-use-reflection-to-get-a-private-member-variable-from-a-derived-class)) and the accepted answers did not work.</p> <p>The linked SO question said:</p> <pre><code>// _commandCollection is an instance, private member BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; // Retrieve a FieldInfo instance corresponding to the field FieldInfo field = GetType().GetField("_commandCollection", flags); // Retrieve the value of the field, and cast as necessary IDbCommand[] cc =(IDbCommand[])field.GetValue(this); </code></pre> <p>However, there is no <code>GetField()</code> method. I tried a method that looked similar, <code>GetRuntimeField()</code> but that did not work.</p> <p>My code (in the inheriting class) is:</p> <pre><code>public List&lt;BaseData&gt; RealAllData { get { // Use reflection to access the private variable FieldInfo field = GetType().GetRuntimeField("mAllData"); return (List&lt;BaseData&gt;)field.GetValue(this); } } </code></pre> <p>If anyone knows why this does not work then I would be grateful. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload