如何在接口上实现静态方法? [英] How can I implement static methods on an interface?

查看:254
本文介绍了如何在接口上实现静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个第三方C ++ DLL,我从C#调用。

I have a 3rd party C++ DLL that I call from C#.

方法是静态的。

我想抽象出来做一些单元测试,所以我创建了一个静态方法的接口,但现在我的程序错误:

I want to abstract it out to do some unit testing so I created an interface with the static methods in it but now my program errors with:


修饰符'static'对此项无效

The modifier 'static' is not valid for this item



MyMethod cannot be accessed with an instance reference; qualify it with a type name instead

我如何实现这种抽象?

我的代码看起来像这样

private IInterfaceWithStaticMethods MyInterface;

public MyClass(IInterfaceWithStaticMethods myInterface)
{
  this.MyInterface = myInterface;
}

public void MyMethod()
{
  MyInterface.StaticMethod();
}


推荐答案

你无法定义静态C#中接口上的成员。接口是实例的合同

You can't define static members on an interface in C#. An interface is a contract for instances.

我建议您按照目前的方式创建接口,但不要使用static关键字。然后创建一个实现接口并调用静态C ++方法的类 StaticIInterface 。要进行单元测试,创建另一个类 FakeIInterface ,它也实现了接口,但是你需要处理你的单元测试。

I would recommend creating the interface as you are currently, but without the static keyword. Then create a class StaticIInterface that implements the interface and calls the static C++ methods. To do unit testing, create another class FakeIInterface, that also implements the interface, but does what you need to handle your unit tests.

一旦定义了这两个类,就可以创建环境所需的类,并将其传递给 MyClass 的构造函数。

Once you have these 2 classes defined, you can create the one you need for your environment, and pass it to MyClass's constructor.

这篇关于如何在接口上实现静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆