首页 > 解决方案 > 如何链接不同班级的两个代表?

问题描述

我有两个不同的课程,比如说OuterInner。的一个实例InnerOuter. 我的目标是链接ActionInnerand 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#eventsdelegatesaction

解决方案


ActionOuter将字段更改为属性。设置并获得如下所示;

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

推荐阅读