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

时间:2009-08-25 11:10:31

标签: c# generics constraints

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

using System;
using System.Collections.Generic;

namespace test {

    class Base<T> {

        public static List<T> DoSomething() {
            List<T> objects = new List<T>();
            // fill the list somehow...
            foreach (T t in objects) {
                if (t.DoSomeTest()) { // error !!!
                    // ...
                }
            }
            return objects;
        }

        public virtual bool DoSomeTest() {
            return true;
        }

    }

    class Derived : Base<Derived> {
        public override bool DoSomeTest() {
            // return a random bool value
            return (0 == new Random().Next() % 2);
        }
    }

    class Program {
        static void Main(string[] args) {
            List<Derived> list = Derived.DoSomething();
        }
    }
}

我的问题是要做这样的事情,我需要指定像

这样的约束
class Base<T> where T : Base {
}

是否有可能以某种方式指定约束?

2 个答案:

答案 0 :(得分:22)

这可能对您有用:

class Base<T> where T : Base<T>

您不能将T限制为开放的通用类型。如果您需要将T约束为Base<whatever>,则需要构建如下内容:

abstract class Base { }

class Base<T> : Base where T : Base { ... }

答案 1 :(得分:8)

我使用以下方法创建的不是链表,而是创建了一个基因链接树。它非常好用。

public class Tree<T> where T : Tree<T>
{
    T parent;
    List<T> children;

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

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

class Coord3 : Tree<Coord3>
{
    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) { }