How can I implement static methods on an interface?

前端 未结 8 1950
生来不讨喜
生来不讨喜 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条回答
  •  猫巷女王i
    2020-12-07 22:22

    As to why you cannot have a static method on an interface: Why Doesn't C# Allow Static Methods to Implement an Interface?

    However, I would suggest removing the static methods in favor of instance methods. If that is not possible, then you could wrap the static method calls inside of an instance method, and then you can create an interface for that and run your unit tests from that.

    ie

    public static class MyStaticClass
    {
        public static void MyStaticMethod()
        {...}
    }
    
    public interface IStaticWrapper
    {
        void MyMethod();
    }
    
    public class MyClass : IStaticWrapper
    {
        public void MyMethod()
        {
            MyStaticClass.MyStaticMethod();
        }
    }
    

提交回复
热议问题