如何将不同类别中的两个代表联系起来



我有两个不同的类,比如OuterInnerInner的一个实例是Outer中的一个字段。我的目标是连接ActionInnerActionOuter;换句话说,当我为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;
}
}

ActionOuter字段更改为属性。设置并获得以下内容;

public Action<double> ActionOuter
{
set => inner.ActionInner = value;
get => inner.ActionInner;
}

考虑为类使用Properties。使用属性可以在检索属性或设置新值时发生某些事情。

例如,如果我们为ActionOuter实现一个属性,那么每次设置ActionOuter时,都可以检查我们是否有inner,并可能设置它的值。

当您使用setter(set访问器((如下所示(时,您可以使用特殊关键字value,该关键字表示ActionOuter被分配给last时传递的值。这是用于设置专用actionOuter的值,如果需要,还可以设置inner.ActionInner

private Action<double> actionOuter;
public Action<double> ActionOuter{
get => actionOuter;
set{
// do something here, maybe set inner's value?
actionOuter = value;
}
}

相关内容

最新更新