如何完整保存网站并做修改,天津网站建设-中国互联,企业多语言网站开源,服装网站建设的规划C#中的委托类似于C中的函数指针#xff0c;是一种引用类型#xff0c;表示对具有特定参数列表和返回类型的方法的引用。
委托包含两部分#xff0c;委托的声明和委托的实例化。
委托的声明示例如下#xff1a;
public delegate string printString(string str); 委托的实…C#中的委托类似于C中的函数指针是一种引用类型表示对具有特定参数列表和返回类型的方法的引用。
委托包含两部分委托的声明和委托的实例化。
委托的声明示例如下
public delegate string printString(string str); 委托的实例有两种方式一种是通过new的方式创建另一种方式是通过注册的方式创建。
通过new创建实例的示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp1
{internal class Program{public delegate string printString(string str);public string PrintOK(string str){string newStr str OK;return newStr;}public string PrintError(string str){string newStr str Error;return newStr;}public void printInfo(string str){printString ps1 new printString(PrintOK);printString ps2 new printString(PrintError);Console.WriteLine(ps1(str));Console.WriteLine(---------------------);Console.WriteLine(ps2(str));Console.WriteLine(---------------------);}static void Main(string[] args){Program p new Program();p.printInfo(hello);Console.ReadKey();}}
}返回值如下
hello OK --------------------- hello Error --------------------- 通过注册的方式创建实例的示例
说明通过方式注册的函数都会被执行但是假如delegate方法有返回值则只返回最后一次注册的返回值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp1
{internal class Program{public delegate int addNum(int i);public static int num 0;public int addOne(int i){num 1;return i 1;}public int addTwo(int i){num 2;return i 2;}public int addNumResult(int i){addNum an null;an addOne;an addTwo;return an(i);}static void Main(string[] args){Program p new Program();int result p.addNumResult(10);Console.WriteLine(result);Console.WriteLine(num);Console.ReadKey();}}
}此时返回
12代表只返回最后一个注册函数的值
3代表所有的注册函数都执行了一遍