• ref和out


     1、引用类型(ref、out)与值类型

    引用类型都是引用传递(两者都是按地址传递的),就是对传递进去的变量的修改会反映在原来的变量上; 
    值类型当不用 out或者 ref的时候就是值传递,就是对传递进去的变量的修改不会反映在原来的变量上,修改的只是原来变量的一个副本。

    2、重载

    ref 和 out 关键字在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法;

    如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载

    3、初始化

    ref 先初始化;
    out 在方法里初始化。

    4、ref 有进有出,out 只出不进

     以下输出结果 :i = 9

                       ref j =  36

                       q1 = 100

               out   q2 = 103 

    复制代码
     1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5
    6 namespace refout
    7 {
    8 class Program
    9 {
    10 static void fun(int m)
    11 {
    12 int k = 4;
    13 m = k * m;
    14 }
    15 static void fun(ref int m)//可重载
    16 {
    17 int g = 4;
    18 m = g * m;
    19 }
    20 static void func(int q)
    21 {
    22 q += 3;
    23 }
    24 static void func(out int q)
    25 {
    26 q = 100;
    27 q += 3;
    28 }
    29 static void Main(string[] args)
    30 {
    31 //引用传递
    32 int i=9,j=9;
    33 int q1=100,q2;
    34 fun(i);
    35 Console.WriteLine("ref i ={0}",i);
    36 //值传递
    37 fun(ref j);
    38 Console.WriteLine("j = {0}",j);
    39 func(q1);
    40 Console.WriteLine("q1 = {0}",q1);
    41 func(out q2);
    42 Console.WriteLine("out q2 = {0}",q2);
    43 }
    44 }
    45 }
    复制代码
  • 相关阅读:
    CentOS 配置自启动Redis
    WPF Popup全屏 弹出方法。解决只显示75%的问题。
    UpdatePanel控件的使用和局部刷新
    关于width与padding
    WPF 快捷方式
    深入浅出WPF——附加事件(Attached Event)
    控件属性使用代码动代绑定
    ICommand.CanExecuteChanged事件订阅对象的变化
    输入德文出现乱码现象的处理方法
    MVVM 模版里的控件怎样触发命令
  • 原文地址:https://www.cnblogs.com/love828/p/3221187.html
Copyright © 2020-2023  润新知