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

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

问题描述

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

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".

为什么不允许?我能不能覆盖的无障碍?

Why it is not allowed? Can't I override the accessibility?

推荐答案

下面是一个例子的为什么的它没有意义的能够覆盖可见:

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型的,会发生什么?你调用一个方法,就好像它是公开的,但它是一个私有方法。如果你想要这个功能,那么它是不是一个真正的私有的方法是什么呢?

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 your 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()
    {
        //...
    }
}

和你结束了这一点:

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

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

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