通过各种技巧编写回调的指南 [英] Guideline for writing callbacks via various tricks

查看:72
本文介绍了通过各种技巧编写回调的指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在决定是否应该使用


  • a多态性(通过覆盖虚拟方法 A )方法。

  • 委托类型参数化的方法 B

  • 事件 C

  • 使用单个方法 D实现接口的类的实例。 Java的把戏!

  • a polymorphic (via overriding the virtual method A) method.
  • a delegate-type-parameterized method B.
  • an event C.
  • an instance of a class implementing an interface with a single method D. A Java's trick!

编写回调时。

using System;

namespace CallBack
{
    interface IOptional
    {
        void D();
    }

    class Base
    {
        protected virtual void A() => Console.WriteLine("Base's extra jobs.");
        public void Do(Action B = null, IOptional optional = null)
        {
            Console.WriteLine("Base's main jobs.");

            // and call the optional jobs
            A();
            B?.Invoke();
            C?.Invoke();
            optional?.D();
        }
        public event Action C;
    }


    class Derived : Base
    {
        protected override void A()
        {
            base.A();

            Console.WriteLine("Derived's extra jobs.");
        }
    }

    class Optional : IOptional
    {
        public void D()
        {
            Console.WriteLine("D");
        }
    }

    class Test
    {
        static void Main()
        {
            Derived d = new Derived();
            d.C += () => Console.WriteLine("C");
            d.Do(() => Console.WriteLine("B"), new Optional());
        }
    }
}



问题



敏捷程序员是否有任何常用指南?

Question

Is there any commonly used guideline for agile programmers?

推荐答案

三个对我来说似乎很不同:)

The use cases of the three seem quite distinct to me :)

核心思想是您想让谁知道这一事件。

The core idea is "who do you want to let know about the event".

如果您想允许所有人进行订阅,请使用事件。这也是我在处理回调时所用的大部分.NET经验。

If you want to allow everyone to be able to subscribe to it, use an event. This is also what most of .NET that I have experience with deal with callbacks.

通过使用多态方法,您只允许子类知道事件。如果某个其他对象想要在发生时做某事,则不会,因为它不是子类并且无法覆盖该方法。

By using the polymorphism approach, you only allow subclasses to know about the event. If some other object wants to do something when it happens, it can't, because it's not a subclass and can't override the method.

使用委托参数方法中,将订阅者的数量限制为1。任何呼叫者都可以订阅该事件,但是订阅者-事件现在是一对一的关系。

By using the delegate parameter approach, you limit the number of subscribers to 1. Any caller can subscribe to the event, but subscriber-event is now a one-to-one relationship.

这篇关于通过各种技巧编写回调的指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆