为什么 C# 不允许静态方法实现接口? [英] Why Doesn't C# Allow Static Methods to Implement an Interface?

查看:79
本文介绍了为什么 C# 不允许静态方法实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why was C# designed this way?

据我所知,接口仅描述行为,并且用于描述实现特定行为的接口的类的契约义务.

As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.

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

If classes wish to implement that behavour in a shared method, why shouldn't they?

这是我想到的一个例子:

Here is an example of what I have in mind:

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

    ....

 }

推荐答案

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

Assuming you are asking why you can't do this:

public interface IFoo {
    void Bar();
}

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

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


为了实现您的示例,我会给 Animal 一个 const 属性,它仍然允许从静态上下文访问它,并在实现中返回该值.

This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.


To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.

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,并把它当作它可能的指示不是个好主意.

For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.

这篇关于为什么 C# 不允许静态方法实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆