私は、次の例のように、派生したオブジェクトの専門コレクションを返すと、それらにいくつかの操作を実行するために基本ジェネリッククラスのメソッドを作成したいと思います:不思議経常テンプレートパターンとジェネリック制約(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 {
}
は何とかそのような制約を指定することが可能ですように私は制約を指定する必要があり、そのようなことをすることですか?
このようなコードの言語サポートを向上させるために、このユーザーボイスの提案を作成しました。自由に投票してください! https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/32188474-support-this-as-a-return-type-to-make-building-f –