1. 程式人生 > WINDOWS開發 >C# ref與out

C# ref與out

參考連結

總結如下:

  • ref 傳入的時候,必須要對其賦值
  • out 離開的時候,必須要對其賦值

例子:

ref

class RefExample
{
    static void Method(ref int i)
    {
        i = 44;//可以不對i賦值
    }

    static void Main()
    {
        int val = 0;
        Method(ref val);
        // val is now 44
    }
}

out

class OutExample
{
    static void Method(out int i)
    {
        i = 44;  //必須對i賦值
    }

    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}