为什么 C# 是这样设计的?
据我了解,接口(interface)仅描述行为,并用于描述实现特定行为的接口(interface)的类的契约(Contract)义务。
如果类希望在共享方法中实现该行为,为什么不呢?
这是我的想法的一个例子:
// 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;
}
....
}
最佳答案
假设您问为什么不能这样做:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
从语义上讲,这对我来说没有意义。在接口(interface)上指定的方法应该在那里指定与对象交互的契约。静态方法不允许您与对象交互——如果您发现自己的实现可以静态化,您可能需要问问自己该方法是否真的属于接口(interface)。
为了实现您的示例,我会给 Animal 一个 const 属性,这仍然允许从静态上下文访问它,并在实现中返回该值。
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
对于更复杂的情况,您总是可以声明另一个静态方法并委托(delegate)给它。在尝试举一个例子时,我想不出有什么理由让你在静态和实例上下文中做一些不平凡的事情,所以我会给你一个 FooBar blob,并把它作为它可能的指示这不是一个好主意。
关于c# - 为什么 C# 不允许静态方法实现接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/259026/