相关疑难解决方法(0)

C#接口的方法的默认实现?

是否可以在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
}
Run Code Online (Sandbox Code Playgroud)

我问这个是因为(至少据我所知)可以用Java实现(见这里).

PS:拥有一个带有某种方法的抽象基类也不是我的答案,因为我们在C#中没有多重继承,它与接口的默认实现(如果可能!)不同.

c# oop interface

31
推荐指数
5
解决办法
4万
查看次数

20
推荐指数
1
解决办法
9448
查看次数

标签 统计

c# ×2

.net ×1

extension-methods ×1

interface ×1

oop ×1

static ×1