Recommendation 44: Understanding the covariance in a delegate
The generic variable in the delegate is partially supported by the covariance. Why is "partial support covariance"? Look at the following example:
classProgram { Public DelegateT getemployeehanlder<t> (stringname); Static voidMain () {Getemployeehanlder<Employee> Getaemployee =Getamanager; Employee e= Getaemployee ("Mike"); } StaticManager Getamanager (stringname) {Console.WriteLine ("I am the manager:"+name); return NewManager () {Name =name}; } StaticEmployee Getaemployee (stringname) {Console.WriteLine ("I am an employee:"+name); return NewEmployee () {Name =name}; } } InterfaceIsalary<t> { voidPay (); } classBasesalarycounter<t>: isalary<t> { Public voidPay () {Console.WriteLine ("Pay Base Salary"); } } classEmployee { Public stringName {Get;Set; } } classProgrammer:employee {}classManager:employee {}
The Getamanager in the above returns a manager, but in use, it is actually assigned to a delegate variable whose generic parameter is employee. Because of the following situation, compiling is not possible:
getemployeehanlder<manager> Getamanager = Getamanager; Getemployeehanlder<Employee> getaemployee = Getamanager;
To get the above code to compile, you also need to specify the OUT keyword for the generic parameter in the delegate:
Public Delegate T getemployeehanlder< out t> (string name);
Unless the delegate declaration is certainly not used for variability, specifying the OUT keyword for a generic parameter in a delegate expands the application of the delegate and is recommended to be used forever in the actual encoding process. In fact, some of the delegate declarations in FCL4.0 have used the OUT keyword to allow delegates to support covariance, as we would often use:
Public Delegate TResult func< out tresult>(); Public Delegate TOutput converter< in Out toutput> (tinput input);
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 44: Understanding covariance in delegates