나는 다음 예에서와 같이 파생 개체의 전문 수집을 반환하고 일부 작업을 수행 할 기본 제네릭 클래스의 메소드를 만들 싶습니다호기심 반복 템플릿 패턴 및 제네릭 제약 조건 (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 –