如何解决如何链接不同班级的两个代表?
我有两个不同的类,比如 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;
}
}
解决方法
将 ActionOuter
字段更改为属性。如下设置和获取;
public Action<double> ActionOuter
{
set => inner.ActionInner = value;
get => inner.ActionInner;
}
,
考虑在您的类中使用 Properties。使用属性可以让您在检索属性或使用新值设置属性时发生某些事情。
例如,如果我们为 ActionOuter
实现一个属性,我们可以在每次设置 ActionOuter
时检查我们是否有一个 inner
并可能设置它的值。
当您使用 setter(set accessor)(如下所示)时,您可以使用特殊关键字 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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。