易采站长站为您分析C#中委托的+=和-=深入研究,本文深入研究+=和-=在执行时都做了哪些事情,加深对C#委托的理解和使用,需要的朋友可以参考下
namespace Wolfy.DelegateDemo
{
public delegate void ShowMsg(string msg);
public delegate int MathOperation(int a, int b);
class Program
{
static ShowMsg showMsg;
static MathOperation mathOperation;
static void Main(string[] args)
{
showMsg += ShowHello;
showMsg += ShowHello1;
showMsg("大家新年好啊");
mathOperation += Add;
mathOperation += Multiply;
int result = mathOperation(1, 2);
Console.WriteLine(result.ToString());
Console.Read();
}
static void ShowHello(string msg)
{
Console.WriteLine("哈喽:" + msg);
}
static void ShowHello1(string msg)
{
Console.WriteLine("哈喽1:" + msg);
写在前面
为什么会突然想说说委托?原因吗,起于一个同事的想法,昨天下班的路上一直在想这个问题,如果给委托注册多个方法,会不会都执行呢?为了一探究性,就弄了个demo研究下。
+=
大家都知道委托都继承自System.MulticastDelegate,而System.MulticastDelegate又继承自System.Delegate,可以通过+=为委托注册多个方法。那么他们是否都执行了呢?执行的结果又是怎样的呢?有返回值和没返回值的是否结果是否一样?那就试着说说+=都干了哪些事?
测试代码
复制代码namespace Wolfy.DelegateDemo
{
public delegate void ShowMsg(string msg);
public delegate int MathOperation(int a, int b);
class Program
{
static ShowMsg showMsg;
static MathOperation mathOperation;
static void Main(string[] args)
{
showMsg += ShowHello;
showMsg += ShowHello1;
showMsg("大家新年好啊");
mathOperation += Add;
mathOperation += Multiply;
int result = mathOperation(1, 2);
Console.WriteLine(result.ToString());
Console.Read();
}
static void ShowHello(string msg)
{
Console.WriteLine("哈喽:" + msg);
}
static void ShowHello1(string msg)
{
Console.WriteLine("哈喽1:" + msg);










