Pregunta

This must be a simply question. I define two delegate types:

delegate void TestHandler(object sender, EventArgs args);
delegate void TestHandlerGen<TArgs>(object sender, TArgs args);

Then I use them:

TestHandler h1 = null;
TestHandlerGen<EventArgs> h2 = delegate { };

// this compiles
h1 = new TestHandler(h2);

// this doesn't compile:
// Cannot implicitly convert type 'X.TestHandlerGen<System.EventArgs>' 
// to 'X.TestHandler'
h1 = h2;

The delegeates have the same signature, why does h1 = h2 not compile?

Why does h1 = new TestHandler(h2) compile just fine?

¿Fue útil?

Solución

From the specification:

15.1 Delegate declarations

Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types

The first example works since you can create a new delegate from a compatible delegate instance. So while h2 is compatible with h1 it is not equal since they have different types:

7.6.10.5 Delegate creation expressions

A delegate-creation-expression is used to create a new instance of a delegate-type. delegate-creation-expression:

new delegate-type (expression)

The binding-time processing of a delegate-creation-expression of the form newD(E), where D is a delegate-type and E is an expression, consists of the following steps:

• If E is a value, E must be compatible (§15.1) with D, and the result is a reference to a newly created delegate of type D that refers to the same invocation list as E. If E is not compatible with D, a compile-time error occurs.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top