2013-07-26 382 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]; } 
    } 
} 

但我不知道這是普遍的解決方案