using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class Vertor
{
public int x;
public Vertor(int x)
{
this.x = x;
}
void Hello(int i)
{
i = 10;
}
}
public class Child:Vertor
{
private new int x;
private int y;
public Child(int sb):base(sb)
{
this.y = sb;
}
public Child(int x,int ys):base(x)
{
this.y = x;
}
}
public class Test : MonoBehaviour {
// Use this for initialization
void Start ()
{
int a = 1;
int b = 1;
Debug.Log("int");
//当新声明值类型时,系统会自动在已有的该类型的变量中查找,如果有相同的,则返回原来已有的内存地址不重新分配。
//当新声明的值类型的值在在栈中已有相同的时候,系统不在单独分配内存,而是用已有的变量地址
//b = 5;//但是当值改变时又会重复上述操作,没有查找到已有的则重新分配内存
Debug.Log((a == b));//true
Debug.Log((a.Equals(b)));//true
string str1 = "abc";
//string str2 = "abc";
string str2 =new string(new char[]{'a','b','c'});
//string是引用类型,但是比较特殊,一些行为类似值类型,
//比如不用new 也可以直接赋值,
//当新声明的string类型的字符串在堆中(因为是引用类型故在堆中)已有时,则系统会返回已有的占中内存地址给该新变量,
//即当新声明的string类型的字符川时,的话,
//跟值类型一样,共用一个栈地址,共用一个内存
Debug.Log("string");
Debug.Log((str1 == str2));//true
Debug.Log((str1.Equals(str2)));//true
//字符串频繁修改时用StringBuilder,string会在每次操作时创建新对象,浪费内存
object obj1 = str1;
object obj2 = str2;
Debug.Log("string 转 object");
Debug.Log((obj1 == obj2));//false//两个对象,内容不相同,故不相等
Debug.Log((obj1.Equals(obj2)));//true 比较地址,此时比较的是两者对应的"abc"的地址,
//因为在系统中只有一个,即是同一个故相等
Debug.Log("Object");
Vertor v1 = new Vertor(1);
Vertor v2= new Vertor(1);
Debug.Log((v1 == v2));//false// == 值类型比较值,引用类型比较栈地址,当然比如在类中也可以重写自定义==
Debug.Log((v1.Equals(v2)));//false//Equals比较的是地址
Vertor v3 = v1;
Vertor v4 = v1;
Debug.Log((v1 == v3));//true
Debug.Log((v1.Equals(v3)));//true
Debug.Log((v4 == v3));//true
Debug.Log((v4.Equals(v3)));//true
Change();
}
//函数都是在栈中,函数中的变量系统都会分配内存
public void Func(int x)
{
x = 10;//如果想修改外部的值这样是无效的
}
public void Func(Vertor ver)
{
ver.x = 10;//引用类型引用的是地址,根据地址查找修改对应的堆中的值,故是有效的更改
}
//传递的是参数是引用类型,故实际是在栈中值类型的引用地址
public void UpdateObject(Vertor ver)
{
//在栈中系统为每个变量分配内存,外部传递进来的内存地址赋给ver
Vertor temp = new Vertor(5);
ver = temp;//此时ver和temp一样,是同一个引用,不再是外部传参的那个引用地址,
//故外部传参过来的那个引用指向的堆内存并没有改变
}
public void Change()
{
Vertor ver = new Vertor(1);
Func(ver.x);//修改值类型无效
Debug.Log("ver.x = " + ver.x);//1
Func(ver);
Debug.Log("ver.x = " + ver.x);//10
UpdateObject(ver);//
Debug.Log("ver.x = " + ver.x);//10
}
}
//string、值类型、引用类型