值类型在赋值的时候,传递的是这个值的本身。
引用类型在赋值的时候,传递的是对这个对象的引用(地址)。
https://www.bilibili.com/video/BV1FJ411W7e5?p=148&spm_id_from=pageDriver
//ref 使实参和形参的地址相同 (值传递->引用传递(不占用堆地址),应该不完全对)
using System;
namespace _087_值传递和引用传递
{
class Program
{
static void Main(string[] args)
{
//值类型:int double char decimal bool enum struct
//引用类型:string 数组 自定义类 集合 object 接口
//值传递和引用传递
int n1 = 1;
int n2 = n1;
Console.WriteLine(n1);
Console.WriteLine(n2);
Console.WriteLine("==============================");
Person p1 = new Person();
p1.Name = "张三";
Person p2 = p1;// 堆里,同一地址
p2.Name = "李四";
p1.Name = "abc";
Person p3 = new Person();
p3.Name = "王五";
Console.WriteLine(p1.Name);
Console.WriteLine(p2.Name);
Console.WriteLine(p3.Name);
Console.WriteLine("==============================");
Person p = new Person();
p.Name = "张三";
Test(p);
Console.WriteLine(p.Name);
Console.WriteLine("==============================");
//string的不可变性 每次赋值重新开辟空间
string s1 = "张三";
string s2 = s1;
s2 = "李四";
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine("==============================");
//ref 使实参和形参的地址相同 (值传递->引用传递,应该不完全对)
int number = 10;
TestTwo(ref number);
Console.WriteLine(number);
Console.ReadKey();
}
/// <summary>
/// 给Person类实例中的Name属性赋值
/// </summary>
/// <param name="pp"></param>
public static void Test(Person pp)
{
Person ppp = pp;
ppp.Name = "李四";
//Person p = pp;
//p.Name = "李四";
}
/// <summary>
/// 给n加10
/// </summary>
/// <param name="n"></param>
public static void TestTwo(ref int n)
{
n += 10;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace _087_值传递和引用传递
{
class Person
{
private string _name;
public string Name { get => _name; set => _name = value; }
}
}