为什么在类中实现的C#接口方法必须是public的? [英] Why must an C# interface method implemented in a class be public?

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

问题描述

我有一个类继承一个接口。接口成员方法在我的类中实现,没有访问修饰符(因此,默认情况下它是私有的)。

I have a class which inherits an interface. An interface member method is implemented in my class without an access modifier (so, by default it's private ) .

我收到错误无法实现一个接口成员,因为它不是公共的。

I am getting the error "cannot implement an interface member because it is not public".

为什么不允许?

推荐答案

这里是为什么感觉能够覆盖可见性:

Here's an example of why it doesn't make sense to be able to override the visibility:

interface someI
{
    void doYourWork();
}
public class A : someI
{
    public void doYourWork()
    {
        //...
    }
}

public class B : someI
{
    private void doYourWork()
    {
        //...
    }
}
void Main()
{
    List<someI> workers = getWorkers();
    foreach(var worker in workers)
        worker.doYourWork();
}

当你的工人是B类型时会发生什么?你正在调用一个方法,就像它是public的,但它是一个私有方法。如果你想要这个功能,那么它不是一个真正的私有方法吗?

What happens when your worker is of type B? You're calling a method as if it were public, but it's a private method. If you want this functionality, then it's not really a private method is it?

如果你只想通过你的接口引用它,你可以定义它如下:

If you only want it to be public when referenced through your interface, then you can define it as such:

public class B : someI
{
    void someI.doYourWork()
    {
        //...
    }
}

你最终会得到这个结果:

And you end up with this:

var b = new B();
b.doYourWork(); // Not accessible
((someI)b).doYourWork(); // Accessible

这篇关于为什么在类中实现的C#接口方法必须是public的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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