1、类class是引用类型,多个引用类型变量的值会互相影响。存储在堆(heap)上
2、结构体struct是值类型,多个值类型变量的值不会互相影响。存储在栈(stack)上
using System; using System.Collections.Generic; using System.Text; namespace VariableScopeSample3 { class Vector { int value; public int Value { get; internal set; } } }
using System; using System.Collections.Generic; using System.Text; namespace VariableScopeSample3 { struct Point { public int X { get; internal set; } public int Y { get; internal set; } } }
using System; namespace VariableScopeSample3 { class Program { static int j = 20; static int Main(string[] args) { int j = 30; Console.WriteLine(j); // return 0; Vector x, y; x = new Vector(); x.Value = 30;//value is a field defind in Vector class y = x; Console.WriteLine(y.Value); y.Value = 50; Console.WriteLine(x.Value); Console.WriteLine("--------------------"); Point a,b; a = new Point(); a.X = 30; b = new Point();//下面有赋值,所以这里可省略 b = a; Console.WriteLine(b.X); b.X = 50; Console.WriteLine(a.X); Console.WriteLine(b.X); return 0; } } }
在C#中,结构体(struct)是值类型,这意味着它们在赋值时是通过值复制的方式来传递的
Point a, b;
声明了两个 Point
类型的变量 a
和 b
。由于结构体是值类型,这两个变量会被初始化为默认值(在本例中,X
和 Y
都是 0
)。
a = new Point();
创建了一个新的 Point
实例,并将其赋值给变量 a
。
a.X = 30;
将 a
的 X
属性设置为 30
。
b = new Point();
创建了另一个新的 Point
实例,并将其赋值给变量 b
。这一步实际上不是必需的,因为你紧接着就重写了 b
的值。
b = a;
将 a
的值复制给 b
。由于结构体是按值传递的,这里发生的是 a
的值(此时 X
是 30
)被复制给 b
。
Console.WriteLine(b.X);
打印 b
的 X
属性,输出 30
。
b.X = 50;
将 b
的 X
属性设置为 50
。由于 b
是 a
的一个副本,这个操作不会影响 a
。
Console.WriteLine(a.X);
打印 a
的 X
属性,输出 30
,因为 a
和 b
是独立的副本。
Console.WriteLine(b.X);
再次打印 b
的 X
属性,输出 50
。
关于 b = new Point();
这一行代码可以省略的问题:
因为在执行 b = a;
之前,b
的值并不重要,因为它会被立即覆盖。省略这一行代码不会影响程序的行为,因为 b
会在赋值时得到 a
的副本。