简体   繁体   English

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

[英]Generic constraint on T to be reference type and value type simultaneously?

I have a problem with understanding how generic constraints work. 我对理解泛型约束如何工作有一个问题。 I think I am missing something important here. 我想我在这里缺少一些重要的东西。 I have enclosed my questions in the comments and would be grateful for providing some explanation. 我在评论中附上了我的问题,并希望提供一些解释。

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

There's nothing wrong with that. 这没什么不对。 Let's look at the definition of the constraints on the type parameters : 让我们看一下类型参数约束的定义:

  • T : class - The type argument T must be a reference type, including any class, interface, delegate, or array type. T : class - 类型参数T必须是引用类型,包括任何类,接口,委托或数组类型。
  • U : struct - The type argument U must be a value type. U : struct - 类型参数U必须是值类型。
  • U : T - The type argument U must be or derive from the class T. U : T - 类型参数U必须是或来自类T.

So all you need to do is find a value type that derives from a reference type. 所以你需要做的就是找到一个从引用类型派生的值类型。 At first that might sound impossible, but if you think a bit harder you will remember that all structs derive from the class object , so this works fine for both your examples: 起初可能听起来不可能,但如果你觉得有点困难,你会记得所有结构派生自类object ,所以这适用于你的两个例子:

new C<object, int>();

However if you swap struct and class then it won't compile: 但是,如果你交换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
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM