如何访问抽象类的私有成员

时间:2013-03-18 02:36:44

标签: c# unit-testing abstract-class

关于我测试抽象类的其他线程(可以找到here),我现在的问题是访问抽象类的私有变量。这与使用Private Accessor有关,但正如我在另一个帖子中所述,我不能在与单元测试相同的文件中创建私有访问器。

以下是我正在谈论的私有变量:

public abstract class Component {

    private eVtCompId mComponentId;   //enum
    private eLayer mLayerId;   //enum
    private IF_SystemMessageHandler mLogger;    //interface

我需要知道如何访问这些,因为我正在创建一个单元测试,涉及获取这些特定变量中的值。

2 个答案:

答案 0 :(得分:1)

您需要使用反射

var instance = new Component();
...
var fieldInfo = typeof(Component).GetField("mComponentId", BindingFlags.Instance | BindingFlags.NonPublic);
var componentId = (eVtCompId)fieldInfo.GetValue(instance);

答案 1 :(得分:1)

如果你不介意有点难看,你可以定义只在编译时在调试模式下编译的函数:

#if DEBUG
            ...
#endif

然后,您可以定义公共方法,并简单地返回私有变量的值,这样它们只能用于单元测试。

相关问题