这个问题在这里已有答案:
我想知道方法重载是否主要是因为调用方的便利应该在接口上实现还是作为扩展方法?我看过了,但是为了方便起见,我找不到任何官方指导方针。
我知道,如果您拥有代码,您可能不应该使用扩展方法,但是为了方便起见,方法就是有区别的。我觉得他们会混乱界面,但也许那只是我。
关于重复:我的问题更多是关于方法重载,当重载是为了方便调用者,并且在实现之间不会有所不同
在接口中使用方法重载的示例实现:
public interface IFoo
{
//This feels cluttered since they don't add any new functionality,
// they are just here to be convenient for the caller.
void Bar(int a);
void Bar(int a, int b);
void Bar(int a, int b, int c);
}
使用扩展方法的示例实现:
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)
{
//...
}
}
如果我们非常确定方法对于所有(包括潜在的)接口实现是相同的,我们应该使用扩展方法:
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 */}
}