c# - 有人可以解释这种通用语法吗?

标签 c# generics delegates action

我已经在谷歌上做了一些这方面的工作,但没有找到任何可以解释语法的内容..

所以我正在使用 Action<T>对于生产者消费者,其中 Action<T>是要执行的消费者操作。我右键单击了 Action<T> -“转到定义”以查看其定义,这就是我看到的内容

public delegate void Action<in T>(T obj);

嗯……我使用泛型已经有一段时间了,但从未使用过也没有见过 <in T> 的语法。

任何人都可以提供一个很好的总结来解释语法及其产生的结果吗?

谢谢。

最佳答案

inout C# 4.0 中引入了泛型类型的变差修饰符,以允许对泛型类型进行协变和逆变。

For generic type parameters, the in keyword specifies that the type parameter is contravariant.

For generic type parameters, the out keyword specifies that the type parameter is covariant.


来自Variance in Generic Interfaces (C# and Visual Basic)在 MSDN 上:

Covariance permits a method to have a more derived return type than that defined by the generic type parameter of the interface.

Contravariance permits a method to have argument types that are less derived than that specified by the generic parameter of the interface.

关于c# - 有人可以解释这种通用语法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298112/

相关文章:

c# - 在循环外添加一个 Console.WriteLine() 会改变循环的计时 - 为什么?

c# - 选择子类的父方法(C#)

c# - 如何使用 SSIS C# 脚本组件将程序集文件加载到 Azure 数据工厂集成运行时?

c# - 使用 Mono 的泛型类型参数没有装箱或类型参数转换

c# - 隐式运算符和 lambda

ios - 回调方法不在 Swift 中从 UIView 调用到 ViewController

c# - 在 Windows Phone 上检测流或字节数组编码

Java - 获取当前的泛型类

generics - Golang通用方法从数据库中获取数据

c# - 我如何重构这些函数以促进代码重用?