为什么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,这将导致与现有程序集不兼容。

您可以将类的静态方法和非静态方法看作是不同的接口。调用时,静态方法解析为单例静态类对象,而非静态方法解析为所处理的类的实例。所以,如果你在一个接口中使用静态和非静态方法,你实际上是在声明两个接口,而实际上我们想要接口被用来访问一个内聚的东西。

接口指定对象的行为。

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

因为接口的目的是允许多态性,能够传递任意数量的已定义类的实例,这些类都已定义,以实现已定义的接口……确保在多态调用中,代码能够找到您正在调用的方法。允许静态方法实现接口是没有意义的,

你怎么称呼它??


public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
    public static void MyMethod() { //Do Something; }
}

 // inside of some other class ...  
 // How would you call the method on the interface ???
    MyClass.MyMethod();  // this calls the method normally 
                         // not through the interface...

    // This next fails you can't cast a classname to a different type... 
    // Only instances can be Cast to a different type...
    MyInterface myItf = MyClass as MyInterface;  

举一个例子,我既没有接口方法的静态实现,也没有Mark Brackett介绍的“所谓的类型方法”:

当从数据库存储中读取数据时,我们有一个通用的DataTable类来处理从任何结构的表中读取数据。所有特定于表的信息都放在每个表的一个类中,每个表还保存来自DB的一行的数据,并且必须实现IDataRow接口。IDataRow中包含了要从数据库中读取的表的结构描述。DataTable在从DB中读取数据之前必须向IDataRow请求数据结构。目前看起来是这样的:

interface IDataRow {
  string GetDataSTructre();  // How to read data from the DB
  void Read(IDBDataRow);     // How to populate this datarow from DB data
}

public class DataTable<T> : List<T> where T : IDataRow {

  public string GetDataStructure()
    // Desired: Static or Type method:
    // return (T.GetDataStructure());
    // Required: Instantiate a new class:
    return (new T().GetDataStructure());
  }

}

每个表只需要读取一次GetDataStructure,实例化一个实例的开销是最小的。但是,在这种情况下它会很好。