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

    ....

 }

当前回答

我猜这是短视。

在最初设计时,接口仅用于类的实例

IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();

只有引入接口作为泛型的约束,向接口中添加静态方法才有实际用途。

(回复评论:)我认为现在更改它需要更改CLR,这将导致与现有程序集不兼容。

其他回答

当类实现接口时,它是在为接口成员创建实例。虽然静态类型没有实例,但在接口中使用静态签名是没有意义的。

我猜这是短视。

在最初设计时,接口仅用于类的实例

IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();

只有引入接口作为泛型的约束,向接口中添加静态方法才有实际用途。

(回复评论:)我认为现在更改它需要更改CLR,这将导致与现有程序集不兼容。

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

接口是一个OOPS概念,这意味着接口的每个成员都应该通过对象或实例得到使用。因此,接口不能有静态方法。

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