[C#] Out 與 ref 差異

  • 27213
  • 0
  • C#
  • 2015-05-17

摘要:[C#]Out 與 ref 差異

※Out 與 ref 都是以 By Reference 作為參數傳遞

※Out 與 ref 不同點

● ref 必須先將參數做初始化而Out則不需要

● out 一定要修改傳入的參數 而 ref 則不用

● ref 需要在執行前初始化參數(給值)而 out 是在程式結束前需要初始化參數(給值)

 

ref sample (Program.cs):


    class Program 
    {
        static void Main(string[] args)
        {
            System.DateTime currentTime = System.DateTime.Now;
            Time t = new Time(currentTime);
            t.DisplayCurrentTime();
            int theHour=0 ;//需要先給初始值
            int theMinute = 0;//需要初始化
            int theSecond = 0;//需要先給初始值
            t.GetTime(ref theHour, ref  theMinute, ref theSecond);
            System.Console.WriteLine("Current time: {0}:{1}:{2}",
            theHour, theMinute, theSecond);
            Console.ReadKey();
        } 
    }

out sample (Program.cs):


    class Program
    {
        static void Main(string[] args)
        {
            System.DateTime currentTime = System.DateTime.Now;
            Time t = new Time(currentTime);
            t.DisplayCurrentTime();
            int theHour;//無須初始化
            int theMinute;//無須初始化
            int theSecond;//無須初始化
            t.GetTime(out theHour, out  theMinute, out theSecond);
            System.Console.WriteLine("Current time: {0}:{1}:{2}",
            theHour, theMinute, theSecond);
            Console.ReadKey();
        }
    }

Time.cs :


 public class Time
    {
        private int Year;
        private int Month;
        private int Date;
        private int Hour;
        private int Minute;
        private int Second;
        // public accessor methods
        public void DisplayCurrentTime()
        {
            System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
            Month, Date, Year, Hour, Minute, Second);
        }
        public int GetHour()
        {
            return Hour;
        }
        public void GetTime(out int h, out int m, out int s)
        {
            h = Hour;
            m = Minute;
            s = Second;
        }
        public void GetTime(ref int h, ref int m, ref int s)
        {
            h = Hour;
            m = Minute;
            s = Second;
        }
        // constructor
        public Time(System.DateTime dt)
        {
            Year = dt.Year;
            Month = dt.Month;
            Date = dt.Day;
            Hour = dt.Hour;
            Minute = dt.Minute;
            Second = dt.Second;
        }
    }