In response to my other answer, Eric Smith correctly notes:
"... because it would require implicitly boxing the receiver type parameter ...". Which is what happens anyway, if you do something like this: Func f = 5.ToString; Which is perfectly legal.
Thinking about this has led me to a new answer. Try this on for size:
Ordinary "instance" methods on structs take, at the CIL level, a "managed pointer" (type &
) as a receiver parameter. This is necessary so that instance methods on structs can assign to fields of the struct. See Partition II, Section 13.3.
Similarly, instance methods on classes take an "object reference" (type O
) as a receiver parameter (the difference being that this is a pointer to the managed heap, and needs to be tracked for GC).
Since both CIL &
s and O
s can be (and are) implemented by pointers, everything is hunky-dory for the delegate implementation. Regardless of whether a delegate captures a static method, a class instance method, or a struct instance method, all it needs to do is pass the pointer to its _target
to the first argument of the function.
But the scenario we are discussing ruins that. A static extension method taking an int
as a first argument requires a CIL argument of type int32
(see Partition III, section 1.1.1). Here is where things go off the rails. I don't see any reason why it wouldn't be possible for the implementation of delegates to realize that this was happening (for example, by inspecting the metadata associated with the MethodInfo being captured) and emit a thunk that would unbox the _target
and pass that as the first argument, but this isn't needed for delegates to classical instance methods on structs, since they expect a pointer anyway and doesn't appear (judging by the example in my earlier incorrect answer) to be implemented. Obviously the specific value type in question would control the exact nature of the required thunk.
Unless I am missing a more fundamental obstacle to implementation (I could imagine that it would pose problems for the verifier, for example), it seems like a reasonable case could be made for extending the runtime to support this case, but all the signs are pointing towards this being a limitation of the runtime and not of the C# compiler per se.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…