PrintOne을 두 번 등록 했으므로 다음 코드는 "PrintOne"메시지를 두 번 인쇄합니다. 여기에 질문이 있습니다C# - 중복 multicastdelegate 처리하는 방법?
질문 1> 왜 기본적으로 연산자 + = (즉, 결합)가 중복 된 메서드 처리기를 확인하지 못합니까?
질문 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