如果我们非常确定所有(包括潜在的)接口实现的方法是相同的,我们应该使用扩展方法:
public interface IFoo {
void Bar(int a);
}
public static class FooExtensions {
public static void Bar(this IFoo foo, int a, int b) {...}
public static void Bar(this IFoo foo, int a, int b, int c) {...}
}
我们可以实现不同的 Bar(int a)
方法
public MyFoo : IFoo {
void Bar(int a) { /* MyFoo algorithm here */}
}
public MyOtherFoo : IFoo {
void Bar(int a) { /* some other - MyOtherFoo - algorithm here */}
}
但是还是Bar(int a, b)
一样Bar(int a, b, c)
的:
new MyFoo().Bar(1, 2); // FooExtensions.Bar(IFoo, int, int) called
new MyOtherFoo().Bar(1, 2); // FooExtensions.Bar(IFoo, int, int) called
如果,比如说,Bar(int a, int b)
可以从实现到实现不同,我们必须将它添加到接口中:
public interface IFoo {
void Bar(int a);
void Bar(int a, int b);
}
...
public MyFoo : IFoo {
void Bar(int a) { /* MyFoo algorithm here */}
void Bar(int a, int b) { /* MyFoo algorithm here */}
}
public MyOtherFoo : IFoo {
void Bar(int a) { /* some other - MyOtherFoo - algorithm here */}
void Bar(int a, int b) { /* some other - MyOtherFoo - algorithm here */}
}
如果几乎所有接口实现都具有相同的算法,那么放置样板代码会很无聊。但是,在C# 8.0中,我们将有一个很好的折衷方案——默认方法实现,例如
public interface IFoo {
void Bar(int a);
void Bar(int a, int b) {
/* Default code here */
}
}
// uses default code for Bar(int a, int b)
public MyFoo : IFoo {
void Bar(int a) { /* MyFoo algorithm here */}
}
// uses its own code for Bar(int a, int b)
public MyOtherFoo : IFoo {
void Bar(int a) { /* some other - MyOtherFoo - algorithm here */}
void Bar(int a, int b) { /* some other - MyOtherFoo - algorithm here */}
}