zoukankan      html  css  js  c++  java
  • ref与out

    1.基本理解

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             Person p = new Person();
     6             p.Name = "zhangsan";
     7             int i = 3;
     8             Test(p, i);
     9             Console.WriteLine(p.Name);
    10             Console.WriteLine(i);
    11             Console.ReadKey();
    12         }
    13 
    14         static void Test(Person p,int i)
    15         {
    16             p.Name = "哈哈哈";
    17             i = 666;
    18         }
    19     }
    20 
    21     class Person
    22     {
    23         public string Name { get; set; }
    24     }
    View Code

    打印结果为: i的值未改变。

     2.使用ref后(ref直接把变量传递到一个方法里)

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             Person p = new Person();
     6             p.Name = "zhangsan";
     7             int i = 3;
     8             Test(ref p, ref i);
     9             Console.WriteLine(p.Name);
    10             Console.WriteLine(i);
    11             Console.ReadKey();
    12         }
    13 
    14         static void Test(ref Person p,ref int i)
    15         {
    16             p = new Person();
    17             p.Name = "哈哈哈";
    18             i = 666;
    19         }
    20     }
    21 
    22     class Person
    23     {
    24         public string Name { get; set; }
    25     }
    View Code

    打印结果为:    i的值也改变了。(ref就相当于把外部的变量传进来了,在函数内部可以改变外部变量的指向)

    3.ref的应用:交换两个变量的值

     1 static void Main(string[] args)
     2         {
     3             
     4             int i1 = 4, i2 = 5;
     5             Swap(ref i1, ref i2);//必须带上ref
     6             Console.WriteLine($"i1的值为{i1}");
     7             Console.WriteLine($"i2的值为{i2}");
     8             Console.ReadKey();
     9         }
    10 
    11         static void Swap(ref int a,ref int b)
    12         {
    13             int temp = a;
    14             a = b;
    15             b = temp;
    16         }
    View Code

    打印结果为:

     4.out和ref的区别

     4.1 out的使用

     1        static void Main(string[] args)
     2         {
     3             
     4             int i = 99;
     5             Test2(out i);
     6             Console.WriteLine($"i的值为{i}");
     7             Console.ReadKey();
     8         }
     9         static void Test2(out int i)
    10         {
    11             i = 8;
    12         }
    View Code

    打印结果为:

     4.2 out用来返回返回值(int.TryParse())

     

  • 相关阅读:
    别用言语考验底线
    QQ登陆接口
    cookie设置今日不提醒功能
    Sublime Text 3常用插件
    浏览器的标准模式与怪异模式的设置与区分方法
    JS中offsetTop、clientTop、scrollTop、offsetTop各属性介绍
    javascript中闭包的工作原理
    javascript判断图片是否加载完成方法整理
    社会十二效应法则
    小故事
  • 原文地址:https://www.cnblogs.com/Mask71/p/12019414.html
Copyright © 2011-2022 走看看