How can I implement static methods on an interface?

前端 未结 8 1951
生来不讨喜
生来不讨喜 2020-12-07 21:26

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

The methods are static.

I want to abstract it out to do some unit testing so I created an interface with the

8条回答
  •  不知归路
    2020-12-07 22:26

    Interfaces can't have static members and static methods can not be used as implementation of interface methods.

    What you can do is use an explicit interface implementation:

    public interface IMyInterface
    {
        void MyMethod();
    }
    
    public class MyClass : IMyInterface
    {
        static void MyMethod()
        {
        }
    
        void IMyInterface.MyMethod()
        {
            MyClass.MyMethod();
        }
    }
    

    Alternatively, you could simply use non-static methods, even if they do not access any instance specific members.

提交回复
热议问题