常用的值类型有:int double char bool decimal struct enum;
常用的引用类型有:string 数组 自定义类 接口 委托;
值类型的值存储在内存的栈上,引用类型的值存储在堆中,栈上存储数据的效率要高于堆。
所谓值传递:把值类型作为参数传递,把值本身进行传递。通过关键字ref可以把值传递改变为引用传递。
而引用传递:把引用类型的值作为参数传递,传递的是引用,也就是常说的地址。
通过VS的既时窗口可以查看某个变量的信息,值类型a,输入&a,可以得出a在栈中的地址好值,引用类型得出的是在栈和队中的地址
static void Main(string[] args)
{
//值传递
int number = 20;
Fun(number);//实参
Console.WriteLine(number);
Console.ReadKey();
}
static void Fun(int num)//形参
{
num += 20;
}
//输出:20
//如果是
static void Main(string[] args)
{
//值传递
int number = 20;
Fun(ref number);//实参
Console.WriteLine(number);
Console.ReadKey();
}
static void Fun(ref int num)//形参
{
num += 20;
}
//输出:40
static void Main(string[] args)
{
Person zsPerson = new Person();
zsPerson.Name = "张三";
Person lsPerson = zsPerson;
lsPerson.Name = "李四";
Console.WriteLine(zsPerson.Name);
Console.WriteLine(lsPerson.Name);
Console.ReadKey();
}
class Person
{
public string Name { get; set; }
}
//输出:李四
李四
static void Main(string[] args)
{
Person zsPerson = new Person();
zsPerson.Name = "杨过";
Test(zsPerson);
Console.WriteLine(zsPerson.Name);
Console.ReadKey();
}
static void Test(Person p)
{
p.Name = "小仙女";
Person p2 = new Person();
p2.Name = "小龙女";
p = p2;
}
}
class Person
{
public string Name { get; set; }
}
//输出:小仙女