为什么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;
}
....
}
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; } }
}
一个静态类是用c#实现的,微软用静态元素创建了一个特殊的类实例,这只是实现静态功能的一个奇怪之处。这不是一个理论观点。
接口应该是类接口的描述符——或者它是如何与之交互的,并且应该包括静态的交互。接口的一般定义(来自merriam - webster):不同事物相遇、交流或相互影响的地方或区域。当您完全忽略类的静态组件或静态类时,我们就忽略了这些坏家伙如何交互的大部分内容。
下面是一个非常清晰的例子,说明了在静态类中使用接口是非常有用的:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
目前,我在编写包含这些方法的静态类时没有进行任何检查,以确保我没有忘记任何东西。就像在面向对象编程之前的糟糕的编程时代。