美文网首页
C#:ref 和 out 的区别

C#:ref 和 out 的区别

作者: 咆哮女孩 | 来源:发表于2019-05-04 03:17 被阅读0次
     public static void Main(string[] args)
            {
               
                int val1 = 0; //一定要初始化
                int val2; //optional,可选
    
                Keywords1(ref val1);
                Console.WriteLine(val1); // val1=0
    
                Keywords2(out val2);
                Console.WriteLine(val2); // val2=9
            }
            static void Keywords1(ref int value) //called method
            {
                Console.WriteLine("i am Keyword1");
            }
            static void Keywords2(out int value) //called method
            {
                value = 9; //must be defined 
            }
    

    output
    i am Keyword1
    0
    9

    Press any key to continue...

    image.png

    out作为方法的参数必须初始化,调用的时候可不赋值。
    ref在传入方法时必须初始化。
    也就是两者在赋值的时间不同out在Parameters时期赋值,ref在Argument时期赋值。

    相关文章

      网友评论

          本文标题:C#:ref 和 out 的区别

          本文链接:https://www.haomeiwen.com/subject/pwmtoqtx.html