2013-07-26 384 views
0

我已阅读相关问题(How to get around lack of covariance with IReadOnlyDictionary?),但我不明白它如何帮助解决我的问题。IReadOnlyDictionary缺乏协变性

这里是Box其可以(使用ITargetBox),并通知有关的变化(使用ITargetSource)进行编辑:

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; 
} 

RoomBox的容器。它也实现了两个接口:

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两个不同的字典。我需要做什么?

回答

0

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

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]; } 
    } 
} 

但我不知道这是普遍的解决方案