如何编写泛型类的约束

时间:2012-12-04 05:22:59

标签: c# generics

这样有一个泛型类 XXValue ,其中Type T可以是值类型或引用类型,例如int,string,struct object

public class XXValue<T>
{
   public T DefaultValue;
}

还有另一个通用类 XXAttribute

public class XXAttribute<T>
{
   public T Value;
}

XXAttribute 的类型T应该是类型 XXValue 的类或子类,因此如何编写 where 语句为的 XXAttribute ?哪一个是正确的?

public class XXAttribute<T> where T : XXValue<T>

public class XXAttribute<VT, AT> where AT : XXValue<VT>

2 个答案:

答案 0 :(得分:2)

  

但是XXAttribute的类型T应该是XXValue类的类或子类

鉴于这一说法,它应该是第二个。

public class XXAttribute<TBase, T> where T : XXValue<TBase>
{
    public T Value;
}

这指定XXAttribute的类型参数应继承自XXValue。但由于XXValue也是通用类型,因此您还需要在XXAtribute中指定类型参数,并将其作为TBase传递,并将其传递。


或者(给出问题的范围很难说,但你可以)改变Value的定义方式:

public class XXAttribute<TBase>
{
    public XXValue<TBase> Value;
}

答案 1 :(得分:0)

第二个是正确的,否则编译器知道T的值会很困惑,一方面T是XXValue<T>,另一方面T是int

public class XXAttribute<V, T> where T : XXValue<V>
{
    public T Value;
}

用法:

XXAttribute<int, XXValue<int>> attr = new XXAttribute<int, XXValue<int>>();
相关问题