C#——如何处理重复的 multicastdelegate?

标签 c#

由于我们注册了两次回调函数PrintOne,下面的代码将打印消息“PrintOne”两次。这里有问题,

问题 1> 为什么默认情况下 operator+=(即 Combine)不检查重复的方法处理程序?

问题2> RegisterCall 方法中如何避免重复调用?我试图在 MulticastDelegate/Delegate 中找到一些方法,它可以告诉我调用列表中已经有一个方法。但是我没找到。 http://msdn.microsoft.com/en-us/library/system.multicastdelegate.aspx

谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace app3
{
    class Car
    {
        public delegate void PrintMethod(string msg);

        public string Name { get; set; }

        private PrintMethod printMethods;

        public Car() { }
        public Car(string name) { Name = name; }

        public void PrintCar()
        {
            if (printMethods != null)
            {
                printMethods(this.ToString());
            }
            else
            {
                Console.WriteLine("No Method will be called");
            }
        }
        public override string ToString()
        {
            return string.Format("Car Name is {0}: ", Name);
        }

        public static void PrintOne(string msg)
        {
            Console.WriteLine("PrintOne");
        }

        public static void PrintTwo(string msg)
        {
            Console.WriteLine("PrintTwo");
        }

        public void RegisterCall(PrintMethod methodToCall)
        {
            printMethods += methodToCall;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Car mycar = new Car { Name = "BMW" };
            mycar.RegisterCall(new Car.PrintMethod(Car.PrintOne)); // **will print for the first time**
            mycar.RegisterCall(new Car.PrintMethod(Car.PrintOne)); // **will print for the second time**
            mycar.PrintCar();

            Console.ReadLine();
        }
    }
}

最佳答案

public void RegisterCall(PrintMethod methodToCall)
{
    printMethods -= methodToCall;
    printMethods += methodToCall;
}

这将确保它在多播委托(delegate)中存在时被删除,然后添加,以确保 1 个实例。

如果同一处理程序的委托(delegate)已存在于多播委托(delegate)中,则添加处理程序不会中止,因为大多数情况下不会发生重复。在某些有效情况下,需要两次调用相同的方法(例如对象或集合上的自定义聚合)。

如果他们决定避免重复,他们将不得不在添加处理程序时抛出异常。这在很多方面都很昂贵,无论是在运行时发生时,还是在我们必须编写的所有丑陋的 try-catch block 中。

关于C#——如何处理重复的 multicastdelegate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5969894/

相关文章:

c# - 访问 token 不包含通过 Microsoft Graph 的 SCP(角色)声明

c# - 如果反射效率低下,什么时候最合适?

c# - 一个容器 View 上的多个 View

c# - 如何对可观察集合进行排序?

c# - 具有泛型的多态性-奇怪的行为

c# - 使用 RegularExpressionValidator 上传文件不适用于 Firefox only IE

c# - 如何将 Foreach 语句转换为 linq 表达式?

c# - Silverlight 弹出窗口实际大小

c# - 从VisualStudio生成的数据库资料到程序员生成的资料

c# - 如何在字符串中添加点