由於我們註冊回調函數PrintOne兩次,以下代碼將兩次打印消息「PrintOne」。這裏有問題,C# - 如何處理重複的multicastdelegate?
問題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();
}
}
}
我很快就會到達那裏。剛開始學習C#。 – q0987 2011-05-11 20:51:42