• C# 45. ref和out的区别


    当调用带有参数的方法时,您需要向方法传递参数。在 C# 中,有三种向方法传递参数的方式:
    在这里插入图片描述

    1. ref和out都是C#中的关键字,对于编译后的程序而言,它们之间没有任何区别,也就是说它们只有语法区别。
    2. ref类似于C++中的指针,对其指向的变量可读可写,且必须在方法调用前赋初值
    3. out类似于函数的返回值,只能写,且必须在方法内赋值。
    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();
    
          }
       }
    }
    
    using System;
    namespace CalculatorApplication
    {
       class NumberManipulator
       {
          public void getValue(out int x )
          {
             int temp = 5;
             x = temp;
          }
       
          static void Main(string[] args)
          {
             NumberManipulator n = new NumberManipulator();
             /* 局部变量定义 */
             int a = 100;
             
             Console.WriteLine("在方法调用之前,a 的值: {0}", a);
             
             /* 调用函数来获取值 */
             n.getValue(out a);
    
             Console.WriteLine("在方法调用之后,a 的值: {0}", a);
             Console.ReadLine();
    
          }
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
  • 相关阅读:
    Shiro入门以及Shiro与web整合
    for_each和transform算法(C++)
    9.8 校招 实习 内推 面经
    Pytest在一个函数中使用相同的fixture两次
    抖音API:item_search_keyword-抖音关键词月搜查询
    HashMap详解
    【servelt原理_9_servlet应用___】
    java.util.ConcurrentModificationException异常原因及解决方法
    suse10sp1编译glib-2
    WebServer 解析HTTP 请求报文
  • 原文地址:https://blog.csdn.net/lljss1980/article/details/126915048