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();
   
  }
  }
  }

按输出传递

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


可空类型

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

来源链接:https://www.cnblogs.com/dmx-03/p/18638778

请登录后发表评论

    没有回复内容