小编典典

为什么C#不允许静态方法实现接口?

c#

为什么用这种方式设计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;
    }

    ....

 }

阅读 511

收藏
2020-05-19

共1个答案

小编典典

假设您要问为什么不能这样做:

public interface IFoo {
    void Bar();
}

public class Foo: IFoo {
    public static void Bar() {}
}

从语义上来说,这对我来说没有意义。接口上指定的方法应该在那里指定与对象交互的协定。静态方法不允许您与对象进行交互-
如果您发现自己处于可以将实现静态化的位置,则可能需要问问自己该方法是否真正属于接口。


为了实现您的示例,我将为Animal提供const属性,该属性仍将允许从静态上下文对其进行访问,并在实现中返回该值。

public class Animal: IListItem {
    /* Can be tough to come up with a different, yet meaningful name!
     * A different casing convention, like Java has, would help here.
     */
    public const string AnimalScreenName = "Animal";
    public string ScreenName(){ return AnimalScreenName; }
}

对于更复杂的情况,您总是可以声明另一个静态方法并委托给它。在尝试举一个示例时,我想不出任何理由在静态和实例上下文中都会做一些不平凡的事情,因此,我将为您省去一个FooBar
blob,并以此来表明它可能不是一个好主意。

2020-05-19