列表条目符合类和接口
本文关键字:接口 列表 | 更新日期: 2023-09-27 17:57:36
我有以下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?我可以很容易地做其中一个。但两者都有?
您可以执行以下操作:
public class MyTool<T,U> where T: ITool where U: NativeTool
{
}
并创建这样的:
var tool = new MyTool<MyWidget, MyWidget>();
以及衍生物,如
public class MyWidget : MyTool<....>
{
}
这似乎做到了。包装器的数量令人讨厌,但它完成了任务,没有复制存储。
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; }
}
}