【发布时间】:2021-05-15 14:24:31
【问题描述】:
我有两个不同的课程,比如Outer 和Inner。 Inner 的一个实例是Outer 中的一个字段。我的目标是链接ActionInner 和ActionOuter;换句话说,当我为ActionOuter 添加一个动作时,我希望它被添加到ActionInner。我该怎么做?
这是我的尝试,但没有成功,因为这两个操作都是空值:
class Program
{
static void Main()
{
Outer outer = new Outer();
void writeToConsole(double foo)
{
Console.WriteLine(foo);
}
// Here I expect to link the 'writeToConsole' action to 'inner' 'ActionInner'
outer.ActionOuter += writeToConsole;
// Here I expect an instance of 'inner' to output '12.34' in console
outer.StartAction();
Console.ReadKey();
}
}
class Inner
{
public Action<double> ActionInner;
public void DoSomeStuff(double foo)
{
ActionInner?.Invoke(foo);
}
}
class Outer
{
readonly Inner inner;
public Action<double> ActionOuter;
public void StartAction()
{
inner.DoSomeStuff(12.34);
}
public Outer()
{
inner = new Inner();
// Here I want to somehow make a link between two actions
inner.ActionInner += ActionOuter;
}
}
【问题讨论】:
-
这篇文章需要更加清晰。
标签: c# events delegates action