【问题标题】:How to link two delegates in different classes?如何链接不同班级的两个代表?
【发布时间】:2021-05-15 14:24:31
【问题描述】:

我有两个不同的课程,比如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;
        }
    }

【问题讨论】:

  • 这篇文章需要更加清晰。

标签: c# events delegates action


【解决方案1】:

ActionOuter 字段更改为属性。设置和获取如下;

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

【讨论】:

    【解决方案2】:

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

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

    当您使用setter(set accessor)(如下所示)时,您可以使用特殊关键字value,它表示在分配ActionOuter 时传递的值。这是您用于设置私有 actionOuter 的值,如果需要,也可能是 inner.ActionInner

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

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2015-05-31
      • 2017-01-22
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多