+ 运算符如何用于组合委托?

How does the + operator work for combining delegates?(+ 运算符如何用于组合委托?)

本文介绍了+ 运算符如何用于组合委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

delegate void SomeDelegate();SomeDelegate a = new SomeDelegate( () => Console.WriteLine("A") );SomeDelegate b = new SomeDelegate( () => Console.WriteLine("B") );SomeDelegate c = a + b;

在最后一行,a + b 翻译成什么?我只是好奇如何在不使用 + 运算符的情况下添加它们.

解决方案

http://msdn.microsoft.com/en-us/library/ms173172(v=VS.80).aspx - 搜索添加:

<块引用>

一个委托在被调用时可以调用多个方法.这是称为多播.添加一个额外的方法到委托的方法列表——调用列表——只需要添加两个使用加法或加法赋值运算符('+' 或'+=').例如:

MethodClass obj = new MethodClass();德尔 d1 = obj.Method1;Del d2 = obj.Method2;Del d3 = 委托方法;//两种类型的赋值都是有效的.德尔 allMethodsDelegate = d1 + d2;allMethodsDelegate += d3;

<块引用>

此时 allMethodsDelegate 中包含三个方法调用列表 - Method1、Method2 和 DelegateMethod.原本的三个代表 d1、d2 和 d3 保持不变.什么时候调用 allMethodsDelegate 时,依次调用所有三个方法.如果委托使用引用参数,则传递引用依次依次对这三种方法中的每一种方法进行任何更改一种方法对下一种方法可见.当任何一种方法抛出未在方法中捕获的异常,即异常被传递给委托的调用者并且没有后续调用列表中的方法被调用.

更新

两个委托都派生自 System.Delegate 您可以使用combine() 方法将两个委托加在一起.

For example:

delegate void SomeDelegate();

SomeDelegate a = new SomeDelegate( () => Console.WriteLine("A") );
SomeDelegate b = new SomeDelegate( () => Console.WriteLine("B") );

SomeDelegate c = a + b;

In the last line, what does a + b translate to? I'm just curious how I would add them without using the + operator.

解决方案

http://msdn.microsoft.com/en-us/library/ms173172(v=VS.80).aspx - Search for addition:

A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods—the invocation list—simply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example:

MethodClass obj = new MethodClass(); 
Del d1 = obj.Method1; 
Del d2 = obj.Method2; 
Del d3 = DelegateMethod;

//Both types of assignment are valid. 
Del allMethodsDelegate = d1 + d2; 
allMethodsDelegate += d3;

At this point allMethodsDelegate contains three methods in its invocation list—Method1, Method2, and DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called.

Update

Both delegates derive from System.Delegate You can use the combine() methods to add two delegates together.

这篇关于+ 运算符如何用于组合委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:+ 运算符如何用于组合委托?

基础教程推荐