为什么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;
}
....
}
从概念上讲,接口没有理由不能定义包含静态方法的契约。
对于当前的c#语言实现,限制是由于允许继承基类和接口。如果“类SomeBaseClass”实现了“接口ISomeInterface”和“类SomeDerivedClass: SomeBaseClass, ISomeInterface”也实现了接口,实现接口方法的静态方法将会编译失败,因为静态方法不能与实例方法具有相同的签名(实例方法将出现在实现接口的基类中)。
静态类在功能上与单例类相同,并且具有与单例类相同的目的,只是语法更简洁。因为单例可以实现接口,所以静态的接口实现在概念上是有效的。
因此,这可以简单地归结为c#的实例名称冲突和跨继承的同名静态方法的限制。c#没有理由不能“升级”以支持静态方法契约(接口)。
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
因为它不可用,所以我采用如下所示的方式使用非静态方法。虽然不太理想,但至少对我来说,我找不到比这更有意义的方法了。
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}