C# 之 Ref Out

如下代码:

   static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var (a, b, c) = ("a","b","c");
            myRef(ref a,out b,c);
            Console.WriteLine(a+b+c);
            Console.ReadKey();

        }

        static void myRef(ref string a, out string b, string c)
        {
            a = "aaa";
            b = "bbb";
            c = "ccc";
        }

  查看IL:

C# 之 Ref     Out
 1     .method private hidebysig static 
 2         void Main (
 3             string[] args
 4         ) cil managed 
 5     {
 6         // Method begins at RVA 0x2050
 7         // Code size 62 (0x3e)
 8         .maxstack 3
 9         .entrypoint
10         .locals init (
11             [0] string a,
12             [1] string b,
13             [2] string c
14         )
15 
16         // (no C# code)
17         IL_0000: nop
18         // Console.WriteLine("Hello World!");
19         IL_0001: ldstr "Hello World!"
20         IL_0006: call void [System.Console]System.Console::WriteLine(string)
21         // (no C# code)
22         IL_000b: nop
23         // string a = "a";
24         IL_000c: ldstr "a"
25         IL_0011: stloc.0
26         // string b = "b";
27         IL_0012: ldstr "b"
28         IL_0017: stloc.1
29         // string text = "c";
30         IL_0018: ldstr "c"
31         IL_001d: stloc.2
32         // myRef(ref a, out b, text);
33         IL_001e: ldloca.s 0
34         IL_0020: ldloca.s 1
35         IL_0022: ldloc.2
36         IL_0023: call void ConsoleApp1.Program::myRef(string&, string&, string)
37         // (no C# code)
38         IL_0028: nop
39         // Console.WriteLine(a + b + text);
40         IL_0029: ldloc.0
41         IL_002a: ldloc.1
42         IL_002b: ldloc.2
43         IL_002c: call string [System.Runtime]System.String::Concat(string, string, string)
44         IL_0031: call void [System.Console]System.Console::WriteLine(string)
45         // (no C# code)
46         IL_0036: nop
47         // Console.ReadKey();
48         IL_0037: call valuetype [System.Console]System.ConsoleKeyInfo [System.Console]System.Console::ReadKey()
49         IL_003c: pop
50         // }
51         IL_003d: ret
52     } // end of method Program::Main
View Code

可以看到,这里ref  和Out 用到了指针。

最后将对象引用(类型 O)值存储在给定地址 ,Out 在方法上 多了一个 [out]

C# 之 Ref Out

上一篇:城市代码cityCode 表格,用于获取中国省市天气的api


下一篇:C#字符串基础