delegate void Dele(string str);
delegate void Alli(int num);
class Program
{
static void Main(string[] args)
{
Dele dele = Test; // O
Alli alli = Test; // X
}
static void Test(object obj) { }
}
Alli alli = Test; // X
Why???
Maybe...
str as object
( O )
num as object
( X )
???
(Sorry, I'm not good at English)
(It looks like your post is mostly code; please add some more details.: OK)
This behaviour is specified in the C# language specification.
Here:
Dele dele = Test;
You are doing a method group conversion . One of the requirements for a method group conversion to be allowed is that
The selected method M must be compatible (Delegate compatibility) with the delegate type D, or otherwise, a compile-time error occurs.
Delegate compatibility is specified like this (emphasis mine):
A method or delegate M is compatible with a delegate type D if all of the following are true:
- D and M have the same number of parameters, and each parameter in D has the same ref or out modifiers as the corresponding parameter in M.
- For each value parameter (a parameter with no ref or out modifier), an identity conversion (Identity conversion) or implicit reference conversion (Implicit reference conversions) exists from the parameter type in D to the corresponding parameter type in M.
- For each ref or out parameter, the parameter type in D is the same as the parameter type in M.
- An identity or implicit reference conversion exists from the return type of M to the return type of D.
There is an implicit reference conversion from string
to object
, because string
is a subclass of object
, but there isn't an implicit reference conversion from int
to object
. int
is a value type, so the conversion is actually a boxing conversion . Therefore, the method group conversion does not work for Alli
and Test
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.