我正在进行单元测试,测试的是一个类,其中包含两个私有成员变量。我创建了一个继承于被测试类的类。
起初,我只将想要访问的变量设置为
相关的SO问题说:
如果有人知道为什么这不起作用,我将非常感激。谢谢。
起初,我只将想要访问的变量设置为
protected
,但我认为如果我能保持它们的私有性并使用反射来访问它们会很酷。我谷歌搜索了一些文章(和这里提出的问题:https://dev59.com/c1HTa4cB1Zd3GeqPTKKP相关的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);
然而,没有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);
}
}
如果有人知道为什么这不起作用,我将非常感激。谢谢。