C#为什么要这样设计?
据我所知,接口只描述行为,并用于描述实现接口的类必须实现某些行为的契约义务。
如果类希望在共享方法中实现该行为,为什么不应该呢?
这里是我想象中的一个例子:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
IListItem.ScreenName() => ScreenName()
(使用C# 7语法)将通过调用静态方法显式实现接口方法。但是,当你加入继承时,情况会变得很棘手(你必须重新实现接口)。 - Jeroen Mostert