2024-11-05《c#学习第四天》

参数传递。

按值传递

  只需要记住形参改变时是不会影响实参的值的,以此来保障实参的值。

按引用传递

  在C#中,使用ref关键字声明引用参数。就是共用实参的地址,不会再去创建一个新的地址。下面我们可以清晰的看到运行结果是成功交换了的。

  using System;
  namespace CalculatorApplication
  {
  class NumberManipulator
  {
  public void swap(ref int x, ref int y)
  {
  int temp;
   
  temp = x; /* 保存 x 的值 */
  x = y; /* 把 y 赋值给 x */
  y = temp; /* 把 temp 赋值给 y */
  }
   
  static void Main(string[] args)
  {
  NumberManipulator n = new NumberManipulator();
  /* 局部变量定义 */
  int a = 100;
  int b = 200;
   
  Console.WriteLine("在交换之前,a 的值: {0}", a);
  Console.WriteLine("在交换之前,b 的值: {0}", b);
   
  /* 调用函数来交换值 */
  n.swap(ref a, ref b);
   
  Console.WriteLine("在交换之后,a 的值: {0}", a);
  Console.WriteLine("在交换之后,b 的值: {0}", b);
   
  Console.ReadLine();
   
  }
  }
  }

img

按输出传递

  基础用法与ref一样,不过是关键字换成了out。要记住ref数据类型是有进有出,out数据类型是只进不出,且out型数据在方法中必须要赋值。


可空类型

  可控类型可以理解为就是赋予一个变量的默认值为null,当然也是可以不为null的,具体用法为:int? i = 3;,它等价于Nullable<int> i = new Nullable<int>(3);。然后做一个对比看一下,int i; //默认值0 int? ii; //默认值null
  上述数据类型又被称作是nullable类型。

posted @   new菜鸟  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· c# 半导体/led行业 晶圆片WaferMap实现 map图实现入门篇
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
点击右上角即可分享
微信分享提示