1

所以我有这个用 .NET 4.7 编译的最小示例:

class Program
{
    static void Main(string[] args)
    {
        IDictionary<int, string> dic = new ConcurrentDictionary<int, string>();
        ConcurrentDictionary<int, string> sameDic = (ConcurrentDictionary<int, string>) dic;

        dic.Add(1, "Hold");
        dic.Add(2, "position");

        dic.Remove(1); // OK 
        sameDic.Remove(2); // Not even compiling !! 
    }
}
  • 那么打电话安全dic.Remove(1)吗?
  • 知道编译器不接受以下代码,如何重现相同的行为?

代码 :

public interface IFoo
{
    void B();
}

public class Bar : IFoo
{
    private void B() // Not allowed 
    {
    }
}
4

2 回答 2

4

您似乎正在寻找显式接口实现1。你可以写:

public interface IFoo
{
    void B();
}

public class Bar : IFoo
{
    void IFoo.B()
    {
    }
}

现在BonBar在将 aBar作为IFoo访问时才可访问。


1而且,事实上,在ConcurrentDictionary<TKey,TValue>文档中,您可以找到IDictionary.Remove列出的.

于 2018-07-24T11:00:07.737 回答
1

接口方法在 aIDictionary<TKey, TValue>.Remove()显式实现ConcurrentDictionary<TKey, TValue>,需要接口引用才能调用该方法。

为什么 .NET Framework 团队决定这样做,从文档中并不清楚,但是是的,调用它是安全的,因为在内部它仍然调用TryRemove().

如何重现相同的行为

请参阅显式接口实现(C# 编程指南)

于 2018-07-24T11:02:35.280 回答