zoukankan      html  css  js  c++  java
  • C# 中ref out区别

    1、使用ref型参数时,传入的参数必须先被初始化。对out而言,必须在方法中对其完成初始化。

    2、使用ref和out时,在方法的参数和执行方法时,都要加Ref或Out关键字。以满足匹配。

    3、out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。

    在C#中,方法的参数传递有四种类型:传值(by value),传址(by reference),输出参数(by output),数组参数(by array)。

    示例:

    代码
    static void Main(string[] args)
    {
    //outTest
    int a, b; //没赋值
    outTest(out a, out b);
    Console.WriteLine(
    "Out Test: a={0}, b={1}",a,b); //输出 a=10,b=20

    int c=8,d=9; //赋值
    outTest(out c,out d);
    Console.WriteLine(
    "Out Test: c={0}, d={1}", c, d);//输出 c=10,d=20

    //RefTest
    int o, p;
    // refTest(ref o, ref p); 错误,Ref 使用前变量必须赋值
    o = 1; p = 2;
    refTest(
    ref o,ref p);
    Console.WriteLine(
    "Ref Test:o={0},p={1}", o, p); //输出 o=30,p=40

    Console.ReadLine();
    }

    static void outTest(out int x,out int y)
    {
    //Console.WriteLine("befor out: x={0},y={1}",x,y); 报错,使用out后,x,y都被清空,需要重新赋值
    x = 10;
    y
    = 20;
    }

    static void refTest(ref int x,ref int y)
    {
    Console.WriteLine(
    "befor ref: x={0},y={1}", x, y); //输出 x=1,y=2
    x = 30;
    y
    = 40;
    }

  • 相关阅读:
    [SDOI2015]星际战争
    [SDOI2016]生成魔咒
    hdu3311
    [ZJOI2011]最小割
    P3331 [ZJOI2011]礼物(GIFT)
    [ZJOI2010]贪吃的老鼠
    状压dp-----三进制
    noip2016 天天爱跑步
    概率期望dp
    poj2186
  • 原文地址:https://www.cnblogs.com/starm/p/1879988.html
Copyright © 2011-2022 走看看