C #: Explicitly specifying an interface in an implementation method

Why, when I implement the interface, if I make this method publicly available, I do not need to explicitly specify the interface, but if I make it private, I should ... as such ( GetQueryString- this is a method from IBar):

public class Foo : IBar
{
    //This doesn't compile
    string GetQueryString() 
    {
        ///...
    }

    //But this does:
    string IBar.GetQueryString() 
    {
        ///...
    }
}

So, why should you explicitly indicate the interface when the method is made private, but not when this method is public?

+3
source share
1 answer

An explicit interface implementation is a kind of intermediate house between public and private: it is publicly accessible if you use the interface link to get it, but this is the only way to access it (even in the same class).

, , , - , . , :

public class Foo : IBar
{
    // Implicit implementation
    public string GetQueryString() 
    {
        ///...
    }

    // Explicit implementation - no access modifier is allowed
    string IBar.GetQueryString() 
    {
        ///...
    }
}

, , IEnumerable<T>, GetEnumerator , :

public class Foo : IEnumerable<string>
{
    public IEnumerator<string> GetEnumerator()
    {
        ...
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Call to the generic version
    }
}

, .

+11

Source: https://habr.com/ru/post/1710662/


All Articles