2009-08-25 4 views
10

私は、次の例のように、派生したオブジェクトの専門コレクションを返すと、それらにいくつかの操作を実行するために基本ジェネリッククラスのメソッドを作成したいと思います:不思議経常テンプレートパターンとジェネリック制約(C#の)

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 { 
} 

は何とかそのような制約を指定することが可能ですように私は制約を指定する必要があり、そのようなことをすることですか?

+0

このようなコードの言語サポートを向上させるために、このユーザーボイスの提案を作成しました。自由に投票してください! https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/32188474-support-this-as-a-return-type-to-make-building-f –

答えて

22

これはあなたのために働くかもしれません:あなたはオープンジェネリック型にTを制約することはできません

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

。あなたはBase<whatever>Tを制約する必要がある場合は、のようなものを構築する必要があります:

abstract class Base { } 

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

まさに私が望むもの、ありがとう:) –

+2

うわー、これは合法ですか? – Qwertie

+1

Qwertie:どうしてですか? –

8

私がいないリンクリストを作成するには、以下の使用していたが、generecicは木をリンク。すごくうまく機能します。

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親と、ルートオブジェクトを初期化することです。あなたを覚えているを行うことはできませんCoord3() : base(this) { }

関連する問題