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 关键字

  • 相关阅读:
    docker入门
    IAR屏蔽警告的方法
    在MDK 中忽略(suppress) 某一个警告
    stm32 F40x CCM数据区的使用
    如何理解Stand SPI Dual SPI 和Quad SPI??
    stm32F1在sram中调试运行代码
    stm32低功耗的一点总结
    C语言中__attribute__ ((at())绝对定位的应用
    系统栈和任务栈——freertos
    软件模拟spi的注意事项
  • 原文地址:https://www.cnblogs.com/kelei12399/p/2316389.html
Copyright © 2011-2022 走看看