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

接口指定对象的行为。

静态方法不指定对象的行为,而是指定以某种方式影响对象的行为。

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

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

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

事实上,确实如此。

截至2022年年中,当前版本的c#完全支持所谓的静态抽象成员:

interface INumber<T>
{
    static abstract T Zero { get; }
}

struct Fraction : INumber<Fraction>
{
    public static Fraction Zero { get; } = new Fraction();

    public long Numerator;
    public ulong Denominator;

    ....
}

请注意,根据你的Visual Studio版本和你安装的。net SDK,你必须至少更新其中一个(或两个),或者你必须启用预览功能(参见在Visual Studio中使用预览功能和预览语言)。

看到更多:

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members https://blog.ndepend.com/c-11-static-abstract-members/ https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces: ~:文本=静态% 20文摘% 20成员% 20允许% 20,像% 20 % 20其他% 20接口% 20的定义。

您想要的是允许通过Type或该类型的任何实例调用静态方法。这至少会导致歧义,这不是一个理想的特征。

关于这是否重要,这是最佳实践,以及这样做是否存在性能问题,将会有无休止的争论。通过简单地不支持它,c#使我们不必担心它。

遵循这一愿望的编译器也可能会失去一些优化,而这些优化可能会带来实例方法和静态方法之间更严格的分离。