Delegate pooling and contraception

The article says the following: http://msdn.microsoft.com/en-us/library/dd799517.aspx

Rejection does not apply to a combination of delegates. That is, if two delegates are of types Action<Derived> and Action<Base> ( Action(Of Derived) and Action(Of Base) in Visual Basic), you cannot combine the second delegate with the first, although the result will be type safe. The difference allows the second delegate to assign a variable of type Action<Derived> , but delegates can only join if their types exactly match.

 Action<B> baction = (taret) => { Console.WriteLine(taret.GetType().Name); }; Action<D> daction = baction; Action<D> caction = baction + daction; 

In the above code, baction and daction take different parameters. But still I can combine them. What am I missing?

TIA.

+6
source share
1 answer

The documentation is not clear, I agree.

The problem is that the execution types of the two combined delegates must match. This means that there are scenarios in which compile-time types are the same, but run-time types do not.

Consider, for example:

 Func<string> f1 = ()=>""; Func<object> f2 = ()=>null; Func<object> f3 = f1; // legal in C# 4 because of covariance Func<object> f4 = f2 + f3; 

This is right at compile time; you add two delegates of the same type of compile time. But at runtime, it will fail because the runtime requires matching runtime types.

This is an unsuccessful hole in a CLR system. I hope we can fix it, but not promises.

+10
source

Source: https://habr.com/ru/post/888599/


All Articles