简体   繁体   中英

How can I change the property once that property has already been passed to a function in C#

I changed MyAction after I pass MyAction to TestMethod , when I call t.Next(3) I hope the changed MyAction method can be called, I cannot pass MyAction as ref or out, because ref or out are not supported in an anonymous function, is there anyway can archive this purpose?
I know I can change the sequence, first set MyAction to a method and then call t.TestMethod(MyAction) , but the requirement in the real world is I have to change MyAction after I called t.TestMethod(MyAction)

class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.TestMethod(MyAction);
            MyAction = new Action(() => { Console.WriteLine(1); });
            t.Next(3);
        }

        public static Action MyAction;
    }
    class Test
    {
        Subject<int> sub = new Subject<int>();
        public void Next(int v)
        {
            sub.OnNext(v);
        }
        public void TestMethod(Action action)
        {
            Enumerable.Range(1, 2).ToObservable().Concat(sub).Subscribe(p =>
            {
                if (action != null) action();
            });

        }
    }

Instead of passing Action action , you could pass a Func<Action> actionProvider as a parameter, and then dispatch it like this:

actionProvider()();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM