Storing a reference to an object in C#

后端 未结 2 1145
面向向阳花
面向向阳花 2020-12-15 14:42

I was wondering how one could store a reference to an object in .net.

That is, I would like something like the following code (note, of course, that the following co

2条回答
  •  误落风尘
    2020-12-15 15:07

    C# has no concept of a reference variable akin to C++'s int& a. There are workarounds. One is to use closures:

    class Test
    {
        private Func get_a;
        private Action set_a;
        public Test(Func get_a, Action set_a)
        {
            this.get_a = get_a;
            this.set_a = set_a;
            this.set_a(this.get_a() + 1);
        }
        public Object getA() { return this.get_a(); }
    }
    /*
     * ...
     */
    static void Main(string[] args)
    {
        int a;
        a=3;
        Test t = new Test(() => a, n => { a = n; });
        Console.WriteLine(a);
        Console.WriteLine(t.getA());
        Console.ReadKey();
    }
    

    I'm not in front of VS, so please excuse any embarrassing faux pas.

提交回复
热议问题