为什么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;
    }

    ....

 }

当前回答

我认为简单的答案是“因为它毫无用处”。 要调用接口方法,需要该类型的实例。从实例方法中,您可以调用任何您想要的静态方法。

其他回答

静态类应该能够做到这一点,这样它们就可以被通用地使用。我不得不实现一个Singleton来实现预期的结果。

我有一堆静态业务层类,实现了CRUD方法,如“创建”,“读取”,“更新”,“删除”的每个实体类型,如“用户”,“团队”等。然后,我为实现CRUD方法的业务层类创建了一个具有抽象属性的基本控件。这让我可以自动从基类中执行“创建”、“读取”、“更新”、“删除”操作。由于静态限制,我不得不使用单例。

接口是已定义可用功能的抽象集合。

该接口中的方法是否表现为静态行为是应该隐藏在接口后面的实现细节。将接口方法定义为静态是错误的,因为您将不必要地强制该方法以某种方式实现。

如果方法被定义为静态的,那么实现接口的类就不会像它应该的那样被封装。在面向对象设计中,封装是一件值得努力的事情(我不会详细说明原因,你可以在这里阅读:http://en.wikipedia.org/wiki/Object-oriented)。因此,在接口中不允许使用静态方法。

因为接口是继承结构,静态方法继承不好。

在接口代表“契约”的程度上,静态类实现接口似乎是非常合理的。

上述论点似乎都忽略了合同的这一点。

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; } }
}