如果属性已经传递给C#中的函数,我如何改变该属性?

问题描述 投票:1回答:1

我换了 MyAction 过了 MyActionTestMethod,当我打电话 t.Next(3) 我希望改变后的 MyAction 方法可以被调用,我不能通过 MyAction 作为 ref 或 out,因为 ref 或 out 在匿名函数中是不支持的,有什么办法可以将这个目的归档?我知道我可以改变顺序,先设置为 MyAction 的方法,然后调用 t.TestMethod(MyAction)但现实世界中的要求是我必须改变 MyAction 在我打电话给 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();
            });

        }
    }
c#
1个回答
0
投票

而不是传给 Action action你可以通过 Func<Action> actionProvider 作为参数,然后像这样调度。

actionProvider()();
© www.soinside.com 2019 - 2024. All rights reserved.