在Windows 8应用程序中的反思

Luk*_*uke 5 c# reflection windows-8 windows-runtime windows-store-apps

我是单元测试一个类,里面有2个私有成员变量.我创建了一个继承自我正在测试的类的类.

起初我只是创建了我想要访问的变量,protected但我认为如果我可以将它们保密并使用反射来访问它们会很酷.我用Google搜索并找到了各种文章(和问题在这里(http://stackoverflow.com/questions/4097682/c-sharp-use-reflection-to-get-a-private-member-variable-from-a-derived -class))和接受的答案不起作用.

链接的SO问题说:

// _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);
Run Code Online (Sandbox Code Playgroud)

但是,没有GetField()方法.我尝试了一种类似的方法,GetRuntimeField()但是没有用.

我的代码(在继承类中)是:

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

如果有人知道为什么这不起作用那么我将不胜感激.谢谢.

Ore*_*tny 1

您还可以将反射代码放入面向 .NET 4 和 Windows 应用商店应用程序的可移植类库中。然后,您将可以访问“旧”反射 API,包括 BindingFlags 等。