凯里公司网站建设,合法购物网站建设,电子商务网站规划的流程,伊春网站制作1、类class是引用类型#xff0c;多个引用类型变量的值会互相影响。存储在堆#xff08;heap#xff09;上
2、结构体struct是值类型#xff0c;多个值类型变量的值不会互相影响。存储在栈#xff08;stack#xff09;上
类结构关键字classstruct类型引用类型值类型存储…1、类class是引用类型多个引用类型变量的值会互相影响。存储在堆heap上
2、结构体struct是值类型多个值类型变量的值不会互相影响。存储在栈stack上
类结构关键字classstruct类型引用类型值类型存储位置托管 堆heap上栈stack上语法都使用new来说明实例都使用new来说明实例 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 classy 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 的副本。