2014-04-08 34 views
1

我有下面的C#類和接口:列表條目符合類和接口?

class NativeTool 
class NativeWidget: NativeTool 
class NativeGadget: NativeTool 
// above classes defined by the API I am using. Below classes and interfaces defined by me. 
interface ITool 
interface IWidget: ITool 
interface IGadget: ITool 
class MyTool: NativeTool, ITool 
class MyWidget: NativeWidget, IWidget 
class MyGadget: NativeGadget, IGadget 

現在,我想MyTool保持孩子的名單。這些孩子將全部符合ITool並從NativeTool繼承。類MyTool,MyWidget和MyGadget都符合這些條件。

我的問題是,有沒有辦法告訴MyTool它的子節點將始終從NativeTool和ITool繼承?我可以輕鬆地做到這一點或其他。但是呢?

+0

我不相信你想要的是以任何方式支持截至目前 - 「NativeTool」和「ITool」之間根本沒有連接。任何限制都必須在運行時檢查,這可能不是你想要的(儘管它可能是你必須解決的問題)。 – decPL

回答

0

這似乎做到這一點。惱人的包裝數量,但它完成了工作,沒有重複存儲。

public interface ITool { } 
public interface IWidget : ITool { } 
public class NativeTool { } 
public class NativeWidget : NativeTool { } 
public class MyTool : NativeTool, ITool, INativeTool { 
    public MyTool() { 
    this.Children = new List<INativeTool>(); 
    } 
    public ITool InterfacePayload { get { return this; } } 
    public NativeTool NativePayload { get { return this; } } 
    public List<INativeTool> Children { get; set; } 
    public NativeTool NativeChild(int index) { 
    return this.Children[index].NativePayload; 
    } 
    public ITool InterfaceChild(int index) { 
    return this.Children[index].InterfacePayload; 
    } 
    public void AddChild(MyTool child) { 
    this.Children.Add(child); 
    } 
    public void AddChild(MyWidget child) { 
    this.Children.Add(child); 
    } 
} 
public class MyWidget : NativeWidget, IWidget, INativeTool { 
    public ITool InterfacePayload { get { return this; } } 
    public NativeTool NativePayload { get { return this; } } 
} 
public interface INativeTool { 
    // the two payloads are expected to be the same object. However, the interface cannot enforce this. 
    NativeTool NativePayload { get; } 
    ITool InterfacePayload { get; } 
} 
public class ToolChild<TPayload>: INativeTool where TPayload : NativeTool, ITool, INativeTool { 
    public TPayload Payload { get; set; } 
    public NativeTool NativePayload { 
    get {return this.Payload;} 
    } 
    public ITool InterfacePayload { 
    get { return this.Payload; } 
    } 
} 
0

你可以這樣做:

public class MyTool<T,U> where T: ITool where U: NativeTool 
{ 
} 

創建此類似:

var tool = new MyTool<MyWidget, MyWidget>(); 

還衍生物,像

public class MyWidget : MyTool<....> 
    { 
    }