具体类如何隐藏它实现的接口的成员

Ufu*_*arı 6 .net c#

我将举一个.NET的例子.

ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
Run Code Online (Sandbox Code Playgroud)

在这里您可以看到ConcurrentDictionary实现字典接口.但是我无法Add<TKey,TValue>从ConcurrentDictionary实例访问方法.这怎么可能?

IDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
dictionary.Add(3, 3); //no errors

ConcurrentDictionary<int, int> concurrentDictionary = new ConcurrentDictionary<int, int>();
concurrentDictionary.Add(3, 3); //Cannot access private method here
Run Code Online (Sandbox Code Playgroud)

更新:

我知道如何访问它,但我不知道显式实现接口可以允许将访问修饰符更改为内部.它仍然不允许将其设为私有.它是否正确?关于该部分的更详细解释将是有帮助的.另外,我想知道一些有效的用例.

stu*_*rtd 7

因为该IDictionary.Add方法是由ConcurrentDictionary 显式实现的.

要从类中访问它而不必将变量声明为IDictionary,请将其强制转换为所需的接口:

((IDictionary)concurrentDictionary).Add(3, 3)
Run Code Online (Sandbox Code Playgroud)


Mat*_*vey 5

这是通过显式接口实现完成的

public interface ISomeInterface
{
    void SomeMethod();
}

public class SomeClass : ISomeInterface
{
    void SomeInterface.SomeMethod()
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当您有SomeClass对象的引用时,您将看不到SomeMethod可用的方法.为了调用它,你必须将对象强制转换为ISomeInterface......

((ISomeInterface)mySomeClass).SomeMethod();
Run Code Online (Sandbox Code Playgroud)

这是C#imo中利用率较低的有用功能之一


Ode*_*ded 4

它被实现为显式接口实现,这意味着您需要该类型的变量IDictionary<TKey, TValue>才能访问它。

请参阅 的文档ConcurrentDictionary<TKey, TValue>,在“显式接口实现”部分下。

如果将并发字典转换为IDictionary<TKey, TValue>,您将能够调用Add它。


我不知道显式实现接口可以允许将访问修饰符更改为内部。但它仍然不允许将其设为私有。它是否正确?

不,这是不正确的。

显式接口实现不会更改访问修饰符。它们改变了您访问以这种方式实现的成员的方式(即要求您使用接口类型的变量)。它们仍然是公共成员,但只能使用接口类型访问,而不能使用实现类型访问。