在C#中是否可能定义一个具有默认实现的接口?(这样我们就可以定义实现该接口的类,而不必实现特定的默认方法)。
我知道扩展方法(例如在此链接中解释)。 但这 不是 我的答案,因为像以下的方法扩展一样,编译器仍会抱怨在MyClass中实现MyMethod:
public interface IMyInterface
{
string MyMethod();
}
public static class IMyInterfaceExtens
{
public static string MyMethod(this IMyInterface someObj)
{
return "Default method!";
}
}
public class MyClass: IMyInterface
{
// I want to have a default implementation of "MyMethod"
// so that I can skip implementing it here
}
我问这个问题是因为(按照我的理解)在Java中可以这样做(请看这里)。
PS:拥有一个带有一些方法的抽象基类也不是我的答案,因为在C#中我们没有多重继承,并且与为接口提供默认实现(如果可能的话!)不同。