![](/img/trans.png)
[英]How can I access members of a private abstract to class for read-only purposes in a public class?
[英]how to access private members of an abstract class
關於測試抽象類的其他線程(可以在此處找到),我現在的問題是訪問抽象類的私有變量。 這與使用Private Accessor
,但是正如我在另一個線程中所述,我無法在與單元測試相同的文件中創建私有訪問器。
這是我正在談論的私有變量:
public abstract class Component {
private eVtCompId mComponentId; //enum
private eLayer mLayerId; //enum
private IF_SystemMessageHandler mLogger; //interface
我需要知道如何訪問它們,因為我正在創建一個單元測試,其中涉及在這些特定變量中獲取值。
您將需要使用反射
var instance = new Component();
...
var fieldInfo = typeof(Component).GetField("mComponentId", BindingFlags.Instance | BindingFlags.NonPublic);
var componentId = (eVtCompId)fieldInfo.GetValue(instance);
如果您不介意丑陋,可以通過以下方式定義僅在調試模式下編譯時才編譯的函數:
#if DEBUG
...
#endif
然后,您可以定義公共方法,並僅返回私有變量的值,這樣它們只能用於單元測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.