Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - Guideline for writing callbacks via various tricks

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...