[英]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?我将
MyAction
传递给TestMethod
后更改了MyAction
,当我调用t.Next(3)
时,我希望可以调用更改后的MyAction
方法,我不能将MyAction
作为 ref 或 out 传递,因为匿名 function 不支持 ref 或 out,反正有没有可以存档这个目的?
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)
我知道我可以更改顺序,首先将
MyAction
设置为一个方法,然后调用t.TestMethod(MyAction)
,但现实世界的要求是我必须在调用t.TestMethod(MyAction)
后更改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:您可以将
Func<Action> actionProvider
作为参数传递,而不是传递Action action
,然后像这样调度它:
actionProvider()();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.