I think I've known the answer for a class, just want to confirm my understanding is correct. Let's say I have a ClassA
and its instance named a
. When a.MethodA()
is invoked:
(1) CLR find the type of ClassA
by the type pointer of a
in the heap(the type have been loaded into the heap)
(2) Find the MethodA
in the type, if not found, go to its base type, until the object
class.
Maybe my understanding is not quite precise, but I think it's basicly correct(Correct me if it's wrong!). And here comes the question of a simple struct.
struct MyStruct
{
public void MethodA() { }
}
I have var x = new MyStruct();
, its value is on the stack, and the type of MyStruct
has been loaded into the heap. When execute x.MethodA()
, of course no boxing. How CLR find MethodA
and get the IL and execute/JIT it? I think the answer is probably:(again, correct me if I'm wrong)
(1) we have the declaring type of x
on the stack. CLR find its type by the info on the stack, and find MethodA
in its type. -- let's call it assumptionA
.
I'll be happy if you tell me my assumptionA
is correct. But even it's wrong, it tells a truth: CLR has a way to find a struct's type without boxing.
Now what about x.ToString()
or x.GetType()
? We know that the value will be boxed, and then it will perform like a class. But why do we need boxing here? Since we can get its type(assumptionA tells us), why not go to its base type and find the method(just like a class)? Why need an expensive box operations here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…