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

    ....

 }

当前回答

这里有一个需要类型方法的例子。我正在创建一组基于源XML的类之一。所以我有一个

  static public bool IsHandled(XElement xml)

函数,在每个类上依次调用。

函数应该是静态的,否则我们会浪费时间创建不合适的对象。 正如@Ian Boyde指出的那样,它可以在工厂类中完成,但这只会增加复杂性。

最好将它添加到接口中,以强制类实现者实现它。这不会造成很大的开销——它只是一个编译/链接时间检查,不会影响虚表。

然而,这也将是一个相当小的改进。由于方法是静态的,我作为调用者,必须显式地调用它,因此如果它没有实现,就会立即得到编译错误。允许在接口上指定它将意味着这个错误在开发周期中稍微提前出现,但与其他损坏的接口问题相比,这是微不足道的。

所以这是一个次要的潜在特性,总的来说最好还是忽略不计。

其他回答

这里有一个需要类型方法的例子。我正在创建一组基于源XML的类之一。所以我有一个

  static public bool IsHandled(XElement xml)

函数,在每个类上依次调用。

函数应该是静态的,否则我们会浪费时间创建不合适的对象。 正如@Ian Boyde指出的那样,它可以在工厂类中完成,但这只会增加复杂性。

最好将它添加到接口中,以强制类实现者实现它。这不会造成很大的开销——它只是一个编译/链接时间检查,不会影响虚表。

然而,这也将是一个相当小的改进。由于方法是静态的,我作为调用者,必须显式地调用它,因此如果它没有实现,就会立即得到编译错误。允许在接口上指定它将意味着这个错误在开发周期中稍微提前出现,但与其他损坏的接口问题相比,这是微不足道的。

所以这是一个次要的潜在特性,总的来说最好还是忽略不计。

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

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

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

举一个例子,我既没有接口方法的静态实现,也没有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,实例化一个实例的开销是最小的。但是,在这种情况下它会很好。