C# T上的泛型约束同时为引用类型和值类型?
我在理解泛型约束是如何工作的方面存在问题。我想我错过了一些重要的东西。我已将我的问题附在评论中,并希望提供一些解释C# T上的泛型约束同时为引用类型和值类型?,c#,constraints,generics,value-type,reference-type,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 t
//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?
//第一个示例:
C类
T:在哪里上课
其中U:struct,T
{
}
//上面的代码编译得很好,
//乍一看,U可能是引用类型和值类型
//同时,。我能想到的唯一原因是T可能是
//接口哪个结构可以实现,对吗?
//第二个例子
CC类
其中T:class,new()
其中U:struct,T
{
}
//我还添加了无参数构造函数的要求
//而且,令我惊讶的是,它仍然汇编了
//我有点莫名其妙。
//什么“U”符合要求
//值类型、引用类型和同时具有构造函数?
这没什么错。让我们看一下以下内容的定义:
-类型参数T必须是引用类型,包括任何类、接口、委托或数组类型T:class
-类型参数U必须是值类型U:struct
-类型参数U必须是或派生自类TU:T
对象派生的,因此这对您的两个示例都适用:
new C<object, int>();
对然后呢?您为T指定了它,它将匹配对象构造函数。没关系。是的,你是对的,我看错了@Mark Byers您说过所有结构都源自对象
。因此,如果我有类CS,其中T:class{}
代码类似于CS obj=new CS()代码>不起作用,而DateTime
可强制转换为对象。@Andrzej Nosal:是的,因为约束t:class
并不意味着t可强制转换为对象。这意味着T必须是引用类型。DateTime不是引用类型。C
也有效;)@Hans Passant:+1很好的观点-可能令人惊讶的是,类型ValueType
是一个引用类型,因此C
也可以工作
// 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
{
}