【问题标题】:IReadOnlyDictionary lack of covarianceIReadOnlyDictionary 缺乏协方差
【发布时间】:2013-07-26 10:37:19
【问题描述】:

我已阅读相关问题 (How to get around lack of covariance with IReadOnlyDictionary?),但我不明白它对我的问题有何帮助。

这是Box,可以编辑(使用IBoxTarget)并通知更改(使用IBoxSource):

interface IBoxTarget
{
    void DoSomething();
}

interface IBoxSource
{
    event Action SomethingIsDone;
}

class Box : IBoxTarget, IBoxSource
{
    public void DoSomething()
    {
        // . . . some logic . . .

        if (SomethingIsDone != null) SomethingIsDone();
    }

    public event Action SomethingIsDone;
}

Room 是Box 的容器。它还实现了两个接口:

interface IRoomTarget
{
    IReadOnlyDictionary<string, IBoxTarget> Boxes { get; }
}

interface IRoomSource
{
    IReadOnlyDictionary<string, IBoxSource> Boxes { get; }
}

class Room : IRoomTarget, IRoomSource
{
    Dictionary<string, Box> boxes = new Dictionary<string, Box>();

    IReadOnlyDictionary<string, IBoxTarget> IRoomTarget.Boxes
    {
        get { return boxes; } // Error: "Cannot implicitly convert type ..."
    }

    IReadOnlyDictionary<string, IBoxSource> IRoomSource.Boxes
    {
        get { return boxes; } // Error: "Cannot implicitly convert type ..."
    }
}

我不想在Room 中创建两个不同的字典。我需要做什么?

【问题讨论】:

    标签: c# dictionary interface covariance


    【解决方案1】:

    在我的特殊情况下,这有帮助:

    interface IRoomTarget
    {
        IBoxTarget this[string name] { get; }
    }
    
    interface IRoomSource
    {
        IBoxSource this[string name] { get; }
    }
    
    class Room : IRoomTarget, IRoomSource
    {
        Dictionary<string, Box> boxes = new Dictionary<string, Box>();
    
        public IBoxTarget IRoomTarget.this[string name]
        {
            get { return boxes[name]; }
        }
    
        IBoxSource IRoomSource.this[string name]
        {
            get { return boxes[name]; }
        }
    }
    

    但我不确定这是通用解决方案

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2017-06-04
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多