T的通用约束同时是引用类型和值类型?

时间:2011-01-09 16:56:09

标签: c# constraints generics value-type reference-type

我在理解泛型约束如何工作方面遇到了问题。我想我在这里缺少一些重要的东西。我已在评论中附上我的问题,并希望提供一些解释。

//1st example:

class C <T, U>
    where T : class
    where U : struct, T
{
}
//Above code compiles well, 
//On first sight it looks like U might be reference type and value type
//at the same time. The only reason I can think of, is that T may be an 
//interface which struct can implement, Am I correct?

//2nd example

class CC<T, U>
    where T : class, new ()
    where U : struct, T
{
}

//I added also a reguirement for parameterless constructor
//and, much to my surprise, it still compiles what is
//a bit inexplicable for me.
//What 'U' would meet the requirement to be 
//value type, reference type and have a contructor at the same time?

1 个答案:

答案 0 :(得分:13)

这没什么不对。我们来看看constraints on the type parameters

的定义
  • T : class - 类型参数T必须是引用类型,包括任何类,接口,委托或数组类型。
  • U : struct - 类型参数U必须是值类型。
  • U : T - 类型参数U必须是或来自T类。

所以你需要做的就是找到一个从引用类型派生的值类型。起初可能听起来不可能,但是如果你觉得有点难,你会记得所有结构都来自类object,所以这对你的两个例子都很好:

new C<object, int>();

但是,如果您交换structclass,则无法编译:

// Error - Type parameter 'T' has the 'struct' constraint so 'T'
//         cannot be used as a constraint for 'U'
class C<T, U>
    where T : struct
    where U : class, T
{
}