什么时候使用ref和out?

时间:2014-11-10 15:26:29

标签: c# out ref

所以我正在为一个非常简单的大学班级实验室工作,并遇到了一些问题。我的老师没有彻底解释你什么时候使用ref和何时用完。赋值是更改预先编写的方法以使用ref,然后确保它运行,然后将其更改为use out。我得到了ref部分,但是如何重写该方法?以下是程序

using System;

static class Program
{
    /// <summary>
    /// Purpose: Entry point to your C# program
    /// </summary>
    static void Main()
    {
        int iVal1 = 5;
        int iVal2 = 7;
        //Call the Swap method with two arguments
        Swap(ref iVal1, ref iVal2);
        Console.WriteLine("Swapped values first {0:D} second {1:D}", iVal1, iVal2);
        Console.WriteLine("Press Enter to continue ...");
        Console.ReadLine();
    }//End Main()

    /// <summary>
    /// Purpose: To swap the two parameters passed to this method
    /// </summary>
    /// <param name="num1">num1 int, first number</param>
    /// <param name="num2">num2 int, second number</param>
    static public void Swap(ref int num1, ref int num2)
    {
        int tempInt = num1;
        num1 = num2;
        num2 = tempInt;
    }
}//End class Program

1 个答案:

答案 0 :(得分:2)

out当你想要初始化该属性的引用时{/ 1}} 更改

}。