zoukankan      html  css  js  c++  java
  • C# ref,out

    static void Main(string[] args)
    {
    int a = 1;
    int b = 2;
    string x = "x";
    string y = "y";

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);

    TestInt(a, b);
    TestString(x, y);

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);

    TestIntRef(ref a, ref b);
    TestStringRef(ref x, ref y);

    Console.WriteLine("Main-->a:{0},b:{1}", a, b);
    Console.WriteLine("Main-->x:{0},y:{1}", x, y);
    }

    public static void TestInt(int a, int b)
    {
    a = 10;
    b = 20;
    Console.WriteLine("TestInt-->a:{0},b:{1}", a, b);
    }

    public static void TestIntRef(ref int a, ref int b)
    {
    a = 100;
    b = 200;
    Console.WriteLine("TestIntRef-->a:{0},b:{1}", a, b);
    }

    public static void TestString(string x, string y)
    {
    x = "123x";
    y = "123y";
    Console.WriteLine("TestString-->x:{0},y:{1}", x, y);
    }

    public static void TestStringRef(ref string x, ref string y)
    {
    x = "ref:123x";
    y = "ref:123y";
    Console.WriteLine("TestStringRef-->x:{0},y:{1}", x, y);
    }
     

    Out:

    static void Main(string[] args)
    {
    int a;
    string x, y;
    TestOut(out a);
    Console.WriteLine(a);  //a等于101s
    }

    public static void TestOut(out int a)
    {
    a = 101;
    }

    总结:out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字

  • 相关阅读:
    tectangular container
    WIFI
    微信小程序动态改变数组或对象中的某个属性值
    常用的正则表达式
    前端登录通过账号显示对应头像
    JS返回页面时自动回滚到历史浏览位置
    JavaScript让登录或搜索文本框自动获得焦点
    react脚手架应用
    npm教程3_脚手架原理以及bootstrap引入
    npm教程2
  • 原文地址:https://www.cnblogs.com/kelei12399/p/2316389.html
Copyright © 2011-2022 走看看