1,值类型里包含引用类型,如:struct包含class对象。
该引用类型将作为值类型的成员变量,堆栈上将保存该成员的引用,而成员的实际数据还是保存在托管堆中.
2,引用类型包含值类型,如:class包含int。
如果是成员变量,做为引用类型的一部分将分配在托管堆上 。
如果是方法里的局部变量,则分配在该段代码的线程栈上 。
如下:
public class ReceiveTest : MonoBehaviour
{
private void Awake()
{
//对于引用类型new才会有新的内存存在,不new而赋值不会有新的内存存在。
//对于值类型在使用“=”赋值时,会自动调用隐式的构造函数,会new一次。
TestFruit tf = new TestFruit(100);
TestFruit tf2 = tf;
tf2.fruit.apple = 200;
tf2.num = 200;
print(tf.fruit.apple);//打印200 说明共用托管堆中同一个MyFruit类实例
print(tf.num);//打印100 说明堆栈上存在各自的num
}
}
public class MyFruit
{
public int apple;
}
public struct TestFruit
{
public int num;
public MyFruit fruit;
public TestFruit(int num)
{
this.num = num;
fruit = new MyFruit();
fruit.apple = num;
}
}