值类型和引用类型区别示例

//值类型和引用类型区别示例
using System;

class RefTypeRectangle  //定义一个引用类型(类属于引用类型)
{
 public int Height;
 public int Width;
}

struct ValTypeRectangle//定义一个值类型(结构属于值类型)
{
 public int Height;
 public int Width;
}

class RefValTest
{
 public static int Main()
 {
  RefTypeRectangle rect1 = new RefTypeRectangle();
  rect1.Width = 10;
  rect1.Height = 15;
  RefTypeRectangle rect2 = rect1;
  Console.WriteLine("Dimensions of rect2 are " + rect2.Width + "x" + rect2.Height);
  //输出 Dimensions of rect 2 are 10x15
  Console.WriteLine("changing dimensions of rect1...");
  rect1.Width = 20;
  rect1.Height = 25;
  Console.WriteLine("Dimensions of rect2 now are " + rect2.Width + "x" + rect2.Height);
  //输出 Dimensions of rect 2 are 20x25。
  //rect1的值得改变rect2的值也跟着该变了,因为变量rect2和rect1仅对内存中同一位置的引用
 ValTypeRectangle rect3 = new ValTypeRectangle();
  rect3.Width = 10;
  rect3.Height = 15;
  ValTypeRectangle rect4 = rect3;
  Console.WriteLine("Dimensions of rect4 are " + rect4.Width + "x" + rect4.Height);
  //输出 Dimensions of rect
  Console.WriteLine("changing dimensions of rect3...");
  rect3.Width = 20;
  rect3.Height = 25;
  Console.WriteLine("Dimensions of rect4 now are " + rect4.Width + "x" + rect4.Height);
  //输出 Dimensions of rect 4 are 10x15。
  //rect3的值得改变,rect4的值没有发生变化,因为rect4是值类型,它有自己的值。
  Console.ReadLine();
  return 0;
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值