如何链接不同班级的两个代表?

问题描述

我有两个不同的类,比如 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 accessor)(如下所示)时,您可以使用特殊关键字 value,它表示 ActionOuter 分配给 last 时传递的值。这是您可以用来设置私有 actionOuterinner.ActionInner(如果需要)的值。

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