奇怪的重复模板模式和generics约束(C#)

我想在基类generics类中创建一个方法来返回派生对象的专用集合并对它们执行一些操作,如下例所示:

using System; using System.Collections.Generic; namespace test { class Base { public static List DoSomething() { List objects = new List(); // fill the list somehow... foreach (T t in objects) { if (t.DoSomeTest()) { // error !!! // ... } } return objects; } public virtual bool DoSomeTest() { return true; } } class Derived : Base { public override bool DoSomeTest() { // return a random bool value return (0 == new Random().Next() % 2); } } class Program { static void Main(string[] args) { List list = Derived.DoSomething(); } } } 

我的问题是要做这样的事情我需要指定一个约束

 class Base where T : Base { } 

有可能以某种方式指定这样的约束吗?

这可能对你有用:

 class Base where T : Base 

您不能将T约束为开放generics类型。 如果你需要将T约束到Base ,你需要构造如下:

 abstract class Base { } class Base : Base where T : Base { ... } 

我使用以下内容创建不是链接列表,而是创建一个generecic链接树。 它非常好用。

 public class Tree where T : Tree { T parent; List children; public Tree(T parent) { this.parent = parent; this.children = new List(); if( parent!=null ) { parent.children.Add(this as T); } } public bool IsRoot { get { return parent == null; } } public bool IsLeaf { get { return children.Count == 0; } } } 

Mechanics(坐标系层次结构)的示例用法

 class Coord3 : Tree { Vector3 position; Matrix3 rotation; private Coord3() : this(Vector3.Zero, Matrix3.Identity) { } private Coord3(Vector3 position, Matrix3 rotation) : base(null) { this.position = position; this.rotation = rotation; } public Coord3(Coord3 parent, Vector3 position, Matrix3 rotation) : base(parent) { this.position = position; this.rotation = rotation; } public static readonly Coord3 World = new Coord3(); public Coord3 ToGlobalCoordinate() { if( IsRoot ) { return this; } else { Coord3 base_cs = parent.ToGlobalCoordinate(); Vector3 global_pos = base_cs.position + base_cs.rotation * this.position; Matrix3 global_rot = base_cs.rotation * this.rotation; return new Coord3(global_pos, global_ori ); } } } 

诀窍是使用null parent初始化根对象。 记住你不能Coord3() : base(this) { }