gdo*_*ica 20 .net c# compiler-construction generics c#-3.0
我在寻找GroupBy返回类型时看到了一种不熟悉的语法:
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>
Run Code Online (Sandbox Code Playgroud)
我知道out方法中的含义,但不是泛型界面.
out泛型中的含义是什么?
Fra*_*ank 15
它表示协变参数.另请参阅MSDN上的说明.基本上它说,这IGrouping<Aderived, Bderived>可以被视为IGrouping<Abase, Bbase>,因此你可以
IGrouping<Aderived, Bderived> gr = MakeGrouping(...);
IGrouping<Abase, Bbase> grBase = gr;
Run Code Online (Sandbox Code Playgroud)
if Aderived是接口还是派生类型Abase.当您想要调用需要类型参数IGrouping<Abase, Bbase>但只有类型对象的方法时,这个功能会派上用场IGrouping<Aderived, Bderived>.在这种情况下,由于类型参数的协方差,两种类型都可以被认为是等价的.
out只表示该类型仅用于输出,例如
public interface Foo<out T>
{
T Bar()
}
Run Code Online (Sandbox Code Playgroud)
还有一个修饰符,意味着该类型仅用于输入,例如
public interface Foo<in T>
{
int Bar(T x)
}
Run Code Online (Sandbox Code Playgroud)
之所以使用这些,是因为与T的接口在T中是协变的,而在T中的接口在T中是逆变的.
| 归档时间: |
|
| 查看次数: |
5980 次 |
| 最近记录: |