16

我在理解通用约束如何工作方面遇到问题。我想我在这里遗漏了一些重要的东西。我已将我的问题附在评论中,并感谢您提供一些解释。

//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?
4

1 回答 1

15

这没什么不好。让我们看一下类型参数的约束的定义:

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

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

new C<object, int>();

但是,如果您交换struct然后class它将无法编译:

// 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
{
}
于 2011-01-09T16:59:48.140 回答