Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 委托可以指向多个方法吗?_C#_Delegates - Fatal编程技术网

C# 委托可以指向多个方法吗?

C# 委托可以指向多个方法吗?,c#,delegates,C#,Delegates,各位程序员好,我正在学习代理。在我的书中,作者声称该方法将打印委托对象维护的方法的名称以及定义该方法的类的名称 static void DisplayDelegateInfo(Delegate delObj) { foreach (Delegate d in delObj.GetInvocationList()) { Console.WriteLine("Method Name: {0}", d.Method); Console.WriteLine("Type Name: {0}", d.

各位程序员好,我正在学习代理。在我的书中,作者声称该方法将打印委托对象维护的方法的名称以及定义该方法的类的名称

static void DisplayDelegateInfo(Delegate delObj)
{
 foreach (Delegate d in delObj.GetInvocationList())
{
 Console.WriteLine("Method Name: {0}", d.Method);
 Console.WriteLine("Type Name: {0}", d.Target);
}
}
该方法正以这种方式使用

static void Main(string[] args)
{
 Console.WriteLine("***** Simple Delegate Example *****\n");
 SimpleMath m = new SimpleMath();
 BinaryOp b = new BinaryOp(m.Add);
 DisplayDelegateInfo(b);
 Console.WriteLine("10 + 10 is {0}", b(10, 10));
 Console.ReadLine();
}
我的问题是,如果DisplayDelegateInfo()在delObj调用列表中循环,在这种情况下,我会在数组中看到多个项吗?这本书似乎没有给出一个这样的例子,任何人都可以修改main()方法来显示这个数组中的多个项吗

感谢任何意见, 谢谢 狮子座

复制类
SimpleMath
主体中的现有方法
Add
,并将其重命名为
Add1
,以实现此功能。这称为多播委托,下面是可用于它的.NETC#实现和操作


Add将保留在委托中,而Add1将被附加到内部列表(FIFO队列)中,委托将保持

MultiCastDelegate是从delegate派生的类,可以容纳多个委托。有一个完整的工作示例。

谢谢,但不会“b=new BinaryOp(m.Add1);”替换m.Add()方法,因此b仍然指向1方法Add1?ops抱歉,是的,它将替换它!让我修改一下我的例子
static void Main(string[] args)
{
 Console.WriteLine("***** Simple Delegate Example *****\n");
 SimpleMath m = new SimpleMath();
 BinaryOp b = new BinaryOp(m.Add);

 // bellow 'b +=' is short for b = b + 
 b += m.Add1; // Add1 same type (signature really) as method Add

 DisplayDelegateInfo(b);
 Console.WriteLine("10 + 10 is {0}", b(10, 10));
 Console.ReadLine();
}