This article is a mirror article of machine translation, please click here to jump to the original article.

View: 2933|Reply: 0

[Communication] .NET/C# generic T covariant out and inverter in interface

[Copy link]
Posted on 8/3/2023 8:35:23 PM | | | |
Requirements: Recently, I was looking at the .NET source code and found that there is an out keyword in the interface generic, such as:public interface IStringLocalizer<out T>, and then studied it.

Generic type parameters in an interface can be declared as covariants or inverters. Covariance allows interface methods to have a return type that is more derived than the return type defined by the generic type parameter. The inverter allows the interface method to have a smaller degree of derivation from the argument type specified by the generic parameter. Generic interfaces with covariant or inverter generic type parameters are called "variants".

Covariance: Use the out keyword to declare the generic type parameter as a covariant.
Inverse: Use the in keyword to declare the generic type parameter as an inverter.

This screenshot from VS2022 is very descriptive - it illustrates what kind of limitations this brings to generics, as shown below:



On commissionFunc<in T, out TResult>This means that the parameter type is T and the return type is TResult.

Reference:
The hyperlink login is visible.
The hyperlink login is visible.






Previous:A new timer in .NET 6, PeriodicTimer, is used
Next:Qv2ray connects the Trojan-Go service on Windows
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com