C# ref

  • 71
  • 0
  • 2016-04-21

將物件當作參數傳入 function,即使沒有特別標註 ref,在 function裡做的修改也是會影響到原本的物件,除非…

除非在 function裡重新 new了一個。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Root
    {
        public Node n { get; set; }
    }

    class Node
    {
        public string p { get; set; }
    }

    class Program
    {
        static void Output(object obj)
        {
            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
        }

        static void Main(string[] args)
        {
            Root r = new Root { n = new Node { p = "Main" } };
            Output(r);

            ChangeRoot1(r);
            Output(r);

            ChangeRoot2(r);
            Output(r);

            ChangeRoot3(r);
            Output(r);

            ChangeRoot4(r);
            Output(r);

            ChangeRoot5(r);
            Output(r);

            ChangeRoot6(ref r);
            Output(r);
            /* output
                {"n":{"p":"Main"}}
                {"n":{"p":"ChangeRoot1"}}
                {"n":{"p":"ChangeRoot2"}}
                {"n":{"p":"ChangeRoot2"}}
                {"n":{"p":"ChangeRoot4"}}
                {"n":{"p":"ChangeRoot4"}}
                {"n":{"p":"ChangeRoot6"}}
             */
        }

        static void ChangeRoot1(Root input)
        {
            input.n.p = "ChangeRoot1";
        }

        static void ChangeRoot2(Root input)
        {
            input.n = new Node { p = "ChangeRoot2" };
        }

        static void ChangeRoot3(Root input)
        {
            input = new Root { n = new Node { p = "ChangeRoot3" } };
        }

        static void ChangeRoot4(Root input)
        {
            input.n.p = "ChangeRoot4";
            input = new Root { n = new Node { p = "ChangeRoot4 ctor" } };
        }

        static void ChangeRoot5(Root input)
        {
            input = new Root { n = new Node { p = "ChangeRoot5 ctor" } };
            input.n.p = "ChangeRoot5";
        }

        static void ChangeRoot6(ref Root input)
        {
            input = new Root { n = new Node { p = "ChangeRoot6" } };
        }

    }
}