奇怪的重复模板模式和泛型约束 (C#) [英] Curiously Recurring Template Pattern and generics constraints (C#)
本文介绍了奇怪的重复模板模式和泛型约束 (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在基本泛型类中创建一个方法来返回派生对象的专门集合并对它们执行一些操作,如下例所示:
I would like to create a method in a base generic class to return a specialized collection of derived objects and perform some operations on them, like in the following example:
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();
}
}
}
我的问题是做这样的事情我需要指定一个约束
My problem is that to do such a thing I would need to specify a constraint like
class Base<T> where T : Base {
}
是否可以以某种方式指定这样的约束?
Is it possible to specify a constraint like that somehow?
推荐答案
这可能对你有用:
class Base<T> where T : Base<T>
您不能将 T
限制为开放的泛型类型.如果您需要将 T
限制为 Base
,则需要构造如下内容:
You can't constrain T
to an open generic type. If you need to constrain T
to Base<whatever>
, you'll need to construct something like:
abstract class Base { }
class Base<T> : Base where T : Base { ... }
这篇关于奇怪的重复模板模式和泛型约束 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文