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

    ....

 }

当前回答

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

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

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

其他回答

从概念上讲,接口没有理由不能定义包含静态方法的契约。

对于当前的c#语言实现,限制是由于允许继承基类和接口。如果“类SomeBaseClass”实现了“接口ISomeInterface”和“类SomeDerivedClass: SomeBaseClass, ISomeInterface”也实现了接口,实现接口方法的静态方法将会编译失败,因为静态方法不能与实例方法具有相同的签名(实例方法将出现在实现接口的基类中)。

静态类在功能上与单例类相同,并且具有与单例类相同的目的,只是语法更简洁。因为单例可以实现接口,所以静态的接口实现在概念上是有效的。

因此,这可以简单地归结为c#的实例名称冲突和跨继承的同名静态方法的限制。c#没有理由不能“升级”以支持静态方法契约(接口)。

我知道这是个老问题,但很有趣。这个例子并不是最好的。我认为如果你展示一个用例会更清楚:

string DoSomething<T>() where T:ISomeFunction
{
  if (T.someFunction())
    ...
}

仅仅使用静态方法实现接口并不能达到你想要的效果;所需要的是将静态成员作为接口的一部分。我当然可以想象出许多用例,特别是当它能够创建东西的时候。我可以提供两种可能有用的方法:

Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default(). For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.

这些方法都不太吸引人。另一方面,我希望如果CLR中存在能够干净地提供这类功能的机制,.net将允许指定参数化的“new”约束(因为知道一个类是否具有具有特定签名的构造函数似乎与知道它是否具有具有特定签名的静态方法在难度上相当)。

这里的大多数答案似乎都没有抓住重点。多态性不仅可以在实例之间使用,还可以在类型之间使用。当我们使用泛型时,这是经常需要的。

假设我们在泛型方法中有类型参数,我们需要对它做一些操作。我们不想实例化,因为我们不知道构造函数。

例如:

Repository GetRepository<T>()
{
  //need to call T.IsQueryable, but can't!!!
  //need to call T.RowCount
  //need to call T.DoSomeStaticMath(int param)
}

...
var r = GetRepository<Customer>()

不幸的是,我只能想出一些“丑陋”的选择:

Use reflection Ugly and beats the idea of interfaces and polymorphism. Create completely separate factory class This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class. Instantiate and then call the desired interface method This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.

例子:

public class Customer 
{
  //create new customer
  public Customer(Transaction t) { ... }

  //open existing customer
  public Customer(Transaction t, int id) { ... }

  void SomeOtherMethod() 
  { 
    //do work...
  }
}

为了使用实例化来解决静态接口问题,我们需要做以下事情:

public class Customer: IDoSomeStaticMath
{
  //create new customer
  public Customer(Transaction t) { ... }

  //open existing customer
  public Customer(Transaction t, int id) { ... }

  //dummy instance
  public Customer() { IsDummy = true; }

  int DoSomeStaticMath(int a) { }

  void SomeOtherMethod() 
  { 
    if(!IsDummy) 
    {
      //do work...
    }
  }
}

这显然是丑陋的,也是不必要的,会使所有其他方法的代码复杂化。显然,这也不是一个优雅的解决方案!

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

  static public bool IsHandled(XElement xml)

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

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

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

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

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

接口指定对象的行为。

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