不管是面向对象还是面向过程编程。值类型和引用类型都是必须理解的基础概念。
如以下C#代码
using System;
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public override string ToString()
{
return $"Point(X: {X}, Y: {Y})";
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public override string ToString()
{
return $"Person(Name: {Name}, Age: {Age})";
}
}
class Program
{
static void Main(string[] args)
{
Point p = new Point(10, 20);
PrintPoint(p);
Console.WriteLine($"Point coordinates: X = {p.X}, Y = {p.Y}");
Person person = new Person("John Doe", 30);
PrintPerson(person);
Console.WriteLine($"Person details: Name = {person.Name}, Age = {person.Age}");
}
static void PrintPoint(Point point)
{
point.X = 1000;
point.Y = 2000;
Console.WriteLine($"Point coordinates: X = {point.X}, Y = {point.Y}");
}
static void PrintPerson(Person person)
{
person.Name = "Joey Yu";
person.Age = 40;
Console.WriteLine($"Person details: Name = {person.Name}, Age = {person.Age}");
}
}
以上代码运行之后,你就会发现结构类型(值类型)和类类型(引用类型)的不同之处。
大家都是先构造了一个实例,p和person。再分别通过PrintPoint和PrintPerson方法传入这个实例进行了重新赋值。
在方法中显示了一下各个实例的属性值。毫无疑问,在方法中打印出来的值 ,都是在方法中重新设置的值。但是在方法执行完成后,再分别打印这两个实例的属性值会发现。结构体的属性值还是原来的那个属性值。而结构体的值通过方法执行后,成为执行之后的值。
结论应该是在结构体实例做为参数传递到方法中的时候,这个结构体复制了一遍。不影响原来的结构体。而类实例做为参数传递到方法中的时候,只是将类的引用标签传递到了方法体中。在方法体中对类的实例的操作,都会影响原来的类的实例。
Comments