我将一个非静态字符串传递到 MessageQueue:
public virtual MessageQueue MessageQueue { get; } = new MessageQueue(ConfigHelper.QLocation);
QLocation 是非静态的;但是,MessageQueue 需要静态参数。
我收到此异常:
Cannot access a non-static field in static context
我的ConfigHelper类是我的配置文件值的包装器。我可以将 ConfigHelper 类设为静态;然而,这将使测试变得更加困难。
有没有办法处理这个问题,同时仍然保持代码可测试性?
最佳答案
您正在尝试以静态方式使用QLocation
(ConfigHelper.QLocation
),而它是非静态字段(如您所写...)
试试这个:
.... = new MessageQueue(new ConfigHelper().QLocation);
它将消除错误。
IMO,您应该通过此 CUT(测试下的类)C'tor 注入(inject) MessageQueue
。您的类依赖于 MessageQueue
。
如果您不想注入(inject) MessageQueue
,我建议您注入(inject)连接字符串而不是配置。
关于c# - 创建更多可测试的代码,同时避免静态/非静态字段初始值设定项问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36413447/