奇怪的是经常性模板模式和泛型约束(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
到基地&LT;凡是&GT;
,你需要构建这样的:
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屋!
查看全文