c# - 为什么 C# 不允许静态方法实现接口(interface)?

标签 c# oop language-features

为什么 C# 是这样设计的?

据我了解,接口(interface)仅描述行为,并用于描述实现特定行为的接口(interface)的类的契约(Contract)义务。

如果类希望在共享方法中实现该行为,为什么不呢?

这是我的想法的一个例子:

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

    ....

 }

最佳答案

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

public interface IFoo {
    void Bar();
}

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

从语义上讲,这对我来说没有意义。在接口(interface)上指定的方法应该在那里指定与对象交互的契约。静态方法不允许您与对象交互——如果您发现自己的实现可以静态化,您可能需要问问自己该方法是否真的属于接口(interface)。


为了实现您的示例,我会给 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; }
}

对于更复杂的情况,您总是可以声明另一个静态方法并委托(delegate)给它。在尝试举一个例子时,我想不出有什么理由让你在静态和实例上下文中做一些不平凡的事情,所以我会给你一个 FooBar blob,并把它作为它可能的指示这不是一个好主意。

关于c# - 为什么 C# 不允许静态方法实现接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/259026/

相关文章:

c# - 使用 fiddler core 修改响应

c# DataContractSerializer 问题

c - 在 ansi C 中为嵌入式设备编写可重用的低级图形库

java - C++ 和 Java 中的 "generic"类型有什么区别?

c#匿名类型问题

macos - 你可以用 AppleScript 做什么?

c# - Asp.net C# 数学题

c# - 将 PostBackTrigger 和 AsyncPostBackTriggers 添加到 UpdatePanel 以使用 checkChanged EventHandler 动态生成复选框

java - 演示模型和多个数据源

.net - 使用NHibernate时,使用哪些常用方法来传播模式更改?