Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection in a Windows 8 app

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.

At first I just made the variables I wanted to access protected 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 (& 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.

The linked SO question said:

// _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);

However, there is no GetField() method. I tried a method that looked similar, GetRuntimeField() but that did not work.

My code (in the inheriting class) is:

public List<BaseData> RealAllData
{
    get
    {
        // Use reflection to access the private variable
        FieldInfo field = GetType().GetRuntimeField("mAllData");
        return (List<BaseData>)field.GetValue(this);
    }
}

If anyone knows why this does not work then I would be grateful. Thanks.

like image 465
Luke Avatar asked Nov 12 '22 20:11

Luke


1 Answers

You can also put your reflection code into a Portable Class Library that targets .NET 4 and Windows Store apps. You'll then have access to the "old" reflection API, including BindingFlags, etc.

like image 175
Claire Novotny Avatar answered Nov 15 '22 11:11

Claire Novotny