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?我可以很容易地做到其中之一。但两者兼而有之?

4

2 回答 2

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; }
  }
}
于 2014-04-09T20:27:37.710 回答
0

您可以执行以下操作:

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

并创建这样的:

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

并且还衍生出,例如

   public class MyWidget : MyTool<....>
   {
   }
于 2014-04-08T15:20:47.543 回答