The difference between Struct and Class in C #, very interesting

zhaozj2021-02-16  109

Don't say big truth first, look at the code:

Classa obja = new classa (); obja.m_nvalue = 1; classa obja2 = obja; obja.m_nvalue = 2; messagebox.show (obja2.m_nvalue.tostring ());

When ClassA is a class, and Classa is a Struct, the result will be different!

Class: The memory is allocated from the heap. Obja2 points to Obja, so the value seen is 2;

Struct: The memory is allocated in the stack, and Obja2 copies an Obja, so the value seen is 1;

转载请注明原文地址:https://www.9cbs.com/read-10296.html

New Post(0)