列表条目是否符合类和接口?

时间:2014-04-08 15:16:18

标签: c# generics interface nested-generics

我有以下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?我可以很容易地做一个或另一个。但两个?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

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

并创建如下:

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

也衍生,如

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

答案 1 :(得分: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; }
  }
}