c# - 类型参数相互定义? A类<T1, T2> 其中T1 : Foo where T2 : T1

标签 c# generics covariance contravariance variance

class A<T1, T2>
    where T1 : Foo
    where T2 : T1

有实际用例吗?

有什么区别

class A<T1, T2>
    where T1 : Foo
    where T2 : Foo

?实际发生了什么变化?

涉及方差时是否一样?

最佳答案

区别在于T2不能只是任何 Foo它必须是 Foo源自 T1 .

例如

public class Foo{}
public class Foo1 : Foo {}
public class Foo2 : Foo {}
public class Foo12 : Foo1 {}
public class A<T1,T2> where T1: Foo where T2 : T1 {}

将允许

var a = new A<Foo1, Foo12>()

但不是

var a  = new A<Foo1, Foo2>()

这也意味着您可以安全地转换类型为 T2 的对象至 T1 .

Is it the same when variance is involved?

方差只对接口(interface)起作用。

关于c# - 类型参数相互定义? A类<T1, T2> 其中T1 : Foo where T2 : T1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700614/

相关文章:

c# - 通用的 BehaviorExtensionElement 可能吗?

kotlin - Kotlin通用类的限制

c# - linq表达式作为参数

generics - 使此函数通用时如何满足特征界限?

c# - UWP FileSavePicker.PickSaveFileAsync() 抛出未指定的错误

java - 编译时的通用类​​型检查

python - 计算 Pandas 时间序列中的协方差

带有队列或列​​表的 C# 流畅接口(interface)

c# - T4模板多次处理输入

c# - 事务必须在 SQL Server 的存储过程中吗?