简体   繁体   English

通用类型参数前的“out”是什么意思?

[英]What does "out" mean before a Generic type parameter?

I've just saw an unfamiliar syntax while looking for GroupBy return type:我刚刚在寻找GroupBy返回类型时看到了一个不熟悉的语法:

public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>

MSDN Source MSDN 源

I know what does out mean in methods, but not in a generics interface.我知道out在方法中是什么意思,但在 generics 接口中不知道。

What does out mean in a generic type? out在泛型中是什么意思?

It denotes a covariant parameter.它表示一个协变参数。 See also the description on MSDN .另请参阅MSDN上的说明。 Essentially it says, that IGrouping<Aderived, Bderived> can be regarded as IGrouping<Abase, Bbase> , hence you can从本质上讲, IGrouping<Aderived, Bderived>可以被视为IGrouping<Abase, Bbase> ,因此您可以

IGrouping<Aderived, Bderived> gr = MakeGrouping(...);
IGrouping<Abase, Bbase> grBase = gr;

if Aderived is an interface or a type derived from Abase .如果Aderived是从Abase派生的接口或类型。 This is a feature that comes in handy when you want to call a method that requires a parameter of type IGrouping<Abase, Bbase> , but you only got an object of type IGrouping<Aderived, Bderived> .当您想调用需要IGrouping<Abase, Bbase>类型参数的方法时,此功能会派上用场,但您只有IGrouping<Aderived, Bderived>类型的 object。 In this case, both types can be considered equivalent due to the covariance of their type parameters.在这种情况下,由于类型参数的协变性,两种类型都可以被认为是等价的。

It is one of the two generic modifiers introduces in C# 4.0 (Visual Studio 2010).它是 C# 4.0 (Visual Studio 2010) 中引入的两个通用修饰符之一。

It signifies that the generic parameter it is declared on is covariant.它表示声明它的泛型参数是协变的。

The in modifier signifies the generic parameter it is declared on is contravariant. in修饰符表示声明它的泛型参数是逆变的。

See out (Generic Modifier) and in (Generic Modifier) on MSDN.请参阅 MSDN 上的(Generic Modifier)in (Generic Modifier)

out just means that the type is only used for output eg out 只是表示该类型仅用于 output 例如

public interface Foo<out T>
{
   T Bar()
}

There also is a modifier in that means that the type is only used for input eg还有一个修饰符,表示该类型仅用于输入,例如

public interface Foo<in T>
{
    int Bar(T x)
}

These are used because Interfaces with in are covariant in T and Interfaces with out are contravariant in T.使用这些是因为带有 in 的接口在 T 中是协变的,而带有 out 的接口在 T 中是逆变的。

out keyword in this context would indicate the corresponding type parameter to be covariant simply speaking - covariance enables you to use a more derived type than that specified by the generic parameter. out关键字在此上下文中表示相应的类型参数是协变的 - 协变使您能够使用比泛型参数指定的派生类型更多的类型。

BTW, see this ten part series from Eric Lippert to understand more about covariance and contra-variance: http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx顺便说一句,请参阅 Eric Lippert 的这十部分系列以了解有关协方差和反方差的更多信息: http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in- c-part-one.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM