我已经在谷歌上做了一些这方面的工作,但没有找到任何可以解释语法的内容..
所以我正在使用 Action<T>
对于生产者消费者,其中 Action<T>
是要执行的消费者操作。我右键单击了 Action<T>
-“转到定义”以查看其定义,这就是我看到的内容
public delegate void Action<in T>(T obj);
嗯……我使用泛型已经有一段时间了,但从未使用过也没有见过 <in T>
的语法。
任何人都可以提供一个很好的总结来解释语法及其产生的结果吗?
谢谢。
最佳答案
in
和 out
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/