Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am confused in deciding whether I should use

  • 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!

when writing callbacks.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...