开发者

Why must an C# interface method implemented in a class be public?

开发者 https://www.devze.com 2023-04-01 10:47 出处:网络
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 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 开发者_StackOverflow中文版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();
}

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


Methods have to be implemented public because they have to be callable through the interface, thus from where the interface is accessible as a type.

You have a few options here to "change" the visibility of that method. Given:

public interface IFoo 
{
    bool IsFoo();
}

A. Implement the method explicitly

public class Foo : IFoo
{
    bool IFoo.IsFoo() { return true; }
}

The method will only be available through the interface (IFoo in this case.)

B. Change the visibility of the interface

Define the interface as internal instead of public. As a consequence, however, Foo will have to be internal too.


Requiring that an interface implementation be public is simply a logical requirement. When you implement an interface, you're telling the compiler "Hey I implement every method on this interface". So making the method private makes it no longer accessible - and logically not implemented. Interfaces serve as a contract to code that uses your object saying you can always call any method defined in the interface on my object. If the implementing method were private, that would not longer be true.

If you want to hide your implementation from, say Intellisense, then you can simply implement the method explicitly as @Bryan mentions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号