为什么接口在C#中不能有静态方法 [英] Why interface cannot have static methods in C#

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

问题描述





任何人都可以帮助我知道为什么C#中的界面不能有静态方法。



我尝试了什么:



我试过这样的话然后我得到编译时错误说修饰符静态不是对此项有效。

Hi,

Can anyone please help me to know why interface in C# cannot have static methods.

What I have tried:

I have tried like this then I got compile time error saying "The modifier static is not a valid for this item".

public interface InterfacesEx
{
    static string Test();
}

任何人都可以帮我理解为什么静态在接口中无效?

Can anyone help me to know why static is not valid in interfaces?

推荐答案

hi,



假设你可以在一个接口中指定一个类型必须有一个特定的静态方法而不是你怎么称呼它?多态性通过实例工作 - 而静态成员显式不使用实例。

这就是接口没有静态方法的原因。


Suppose you could specify in an interface that a type had to have a particular static method than how would you call it? Polymorphism works through instances - whereas static members explicitly don't use instances.
that's the reason interfaces don't have static methods.


因为接口是一个接口合同或消费者(呼叫者)与提供者(被呼叫者)之间的协议。界面描述了calle将提供什么以及如何提供功能。不需要由第三方提供的静态成员。静态成员不能被提供者覆盖,因此他们不属于某个界面。



。NET Questions(CLOSED) - 为什么你不能在接口中使用静态方法? [ ^ ]
Because an interface is a "contract" or an agreement between the consumer (caller) and the provider (callee). An interface describes what and how the calle will provide functionality. There is no need for static members provided by a third party. Static members cannot be overridden by a provider so they do not belong in an interface.

.NET Questions (CLOSED) - Why can't you have static methods in an Interface?[^]


另一种查看方式:



如果接口可以采用静态方法:

Another way of looking at it:

If an interface could have a static method:
interface IFoo
{
    static void Bar();
}

class Foo1 : IFoo
{
    public static void Bar() { ... }
}

class Foo2 : IFoo
{
    public static void Bar() { ... }
}

并且你调用它:

IFoo.Bar();

无法知道最终会调用哪个实现。是否会调用 Foo1.Bar Foo2.Bar



您可能决定要让它调用两个实现。哪个可能工作,直到您引入返回值,或 ref / out 参数:

there would be no way to known which implementation you would end up calling. Would that call Foo1.Bar or Foo2.Bar?

You might decide you want it to call both implementations. Which might work, until you introduce return values, or ref / out parameters:

interface IFoo
{
    static int Bar();
}

class Foo1 : IFoo
{
    public static int Bar() { return 42; }
}

class Foo2 : IFoo
{
    public static int Bar() { return 84; }
}

int x = IFoo.Bar(); // What is the value of x?



接口是您可以使用 类的实例完成的事情的合约。静态接口或接口上的静态成员实际上没有任何逻辑意义。


An interface is a contract for things you can do with an instance of a class. A static interface, or static members on an interface, doesn't really make any logical sense.


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

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