C#值类型和引用类型,类和结构体
创始人
2024-11-12 14:40:25
0

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)是值类型,这意味着它们在赋值时是通过值复制的方式来传递的

  1. Point a, b; 声明了两个 Point 类型的变量 a 和 b。由于结构体是值类型,这两个变量会被初始化为默认值(在本例中,X 和 Y 都是 0)。

  2. a = new Point(); 创建了一个新的 Point 实例,并将其赋值给变量 a

  3. a.X = 30; 将 a 的 X 属性设置为 30

  4. b = new Point(); 创建了另一个新的 Point 实例,并将其赋值给变量 b。这一步实际上不是必需的,因为你紧接着就重写了 b 的值。

  5. b = a; 将 a 的值复制给 b。由于结构体是按值传递的,这里发生的是 a 的值(此时 X 是 30)被复制给 b

  6. Console.WriteLine(b.X); 打印 b 的 X 属性,输出 30

  7. b.X = 50; 将 b 的 X 属性设置为 50。由于 b 是 a 的一个副本,这个操作不会影响 a

  8. Console.WriteLine(a.X); 打印 a 的 X 属性,输出 30,因为 a 和 b 是独立的副本。

  9. Console.WriteLine(b.X); 再次打印 b 的 X 属性,输出 50

关于 b = new Point(); 这一行代码可以省略的问题:

因为在执行 b = a; 之前,b 的值并不重要,因为它会被立即覆盖。省略这一行代码不会影响程序的行为,因为 b 会在赋值时得到 a 的副本。

相关内容

热门资讯

透视脚本!wepoker软件安... 透视脚本!wepoker软件安装包(底牌)详细透视辅助挂(有挂技巧)该软件可以轻松地帮助玩家将wep...
三分钟脚本!aapoker脚本... 三分钟脚本!aapoker脚本,aa poker辅助,wepoke教程(有挂解密)aa poker辅...
重大来袭!wepoker网页版... 重大来袭!wepoker网页版透视方法,wepoker高级辅助,微扑克教程(有挂黑科技)1、重大来袭...
7分钟攻略!wpk模拟器,(W... 7分钟攻略!wpk模拟器,(WPk)其实存在有挂(详细透视辅助下载插件)1、让任何用户在无需wpk模...
热点推荐!!hhpoker万能... 热点推荐!!hhpoker万能辅助器,hhpoker买挂,靠谱教程(有挂解说);1、全新机制【hhp...
透视脚本!aapoker ai... 透视脚本!aapoker ai插件(透视)详细公共底牌辅助挂(有挂透明)1)aapoker ai插件...
透视插件!wepokerplu... 透视插件!wepokerplus透视脚本免费,(wepoker)切实是有挂(详细透视底牌辅助app)...
1分钟攻略!wpk辅助器,wp... 1分钟攻略!wpk辅助器,wpk透视辅助方法,解密教程(有挂科普)1)wpk透视辅助方法辅助挂:进一...
玩家必看分享!hhpoker免... 玩家必看分享!hhpoker免费透视脚本,HH平台挂,技巧教程(有挂工具)1、hhpoker免费透视...
透视脚本!aapoker怎么选... 透视脚本!aapoker怎么选牌(透视)详细可以选牌辅助器安装(有挂技巧)1、aapoker怎么选牌...