Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - Why and how does a value type get boxed when you override the virtual method calls into the base type's implementation of the method?

I'm reading a book which talks about struct value type:

if your override of the virtual method calls into the base type's implementation of the method, then the value type instance does get boxed when calling the base type's implementation so that a reference to a heap object gets passed to the this pointer into the base method.

So below is simple code that demostrates:

internal struct Point 
{
   private readonly Int32 m_x, m_y;
   public Point(Int32 x, Int32 y) {
      m_x = x;
      m_y = y;
   }
   
   //Override ToString method and call base method fromSystem.ValueType
   public override string ToString() {
      return base.ToString();    //doesn't make sense, just for demo purpose
   }
}

class Program
{
    static void Main(string[] args) {
       Point p1 = new Point(10, 10);
       p1.ToString();       
    }
}

My question is, what does "a reference to a heap object gets passed to the this pointer into the base method" mean? I simply call the base method as base.ToString();, I didn't pass this pointer argument in the base method, or how a this pointer get passed into the base method?

question from:https://stackoverflow.com/questions/65939540/why-and-how-does-a-value-type-get-boxed-when-you-override-the-virtual-method-cal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...