首页 > 代码库 > 委托的使用 - 浅谈
委托的使用 - 浅谈
一,声明委托
对于委托,定义它就是要告诉编译器,这种类型的委托表示哪种类型的方法.然后,必须创建该委托的一个或多个委托实例,编译器将在后台创建表示该委托的一个类.
因为定义委托基本上是定义一个新类,所以可以在定义类的任何相同地方定义委托.
在术语方面,和"类,对象"不同."类"表示的是较为广义的定义,"对象"表示类的实例.但是委托只有一个术语,在创建委托实例时,所创建的委托的实例仍然称为委托.
如下显示委托的声明方式:
//声明委托.private delegate string GetAString();
二,使用委托
如下例子:
1 int x = 5;2 //通过委托的方式.3 GetAString stringMethod = new GetAString(x.ToString);4 Console.WriteLine(stringMethod());
也可以使用委托推断,只需将地址传递给委托类型的变量(在后台,C#编译器会做同样的处理,即会在后台创建一个委托实例 "new GetAString(x.ToString)"):
1 //使用委托推断,只需将地址传递给委托实例.2 GetAString secondMethod = x.ToString;
实际上,调用委托时,给委托实例提供圆括号与调用委托的Invoke()方法,是完全相同的:
1 Console.WriteLine(stringMethod()); //委托方式1(使用圆括号的方式).2 Console.WriteLine(stringMethod.Invoke()); //委托方式2(使用调用Invoke()方法的方式).
原因是对于委托变量stringMethod,C#编译器会调用stringMethod.Invoke()代替stringMethod().
值得注意的是,在给一个委托类型的变量赋值的时候,方法的名称不能带有"()"括号,上述例子,调用 x.ToString()方法,会返回一个不能赋予委托变量的字符串对象(而不是方法的地址).
委托的一个特征是,它们是类型安全的,可以确定被调用的方法的签名是正确的.但是委托不关心在什么类型上调用改方法,甚至不考虑方法是静态的,还是实例方法.
如下例子演示了委托可以使用实例方法,也可以使用静态方法:
Currency结构的声明:
1 namespace Wrox.ProCSharp.Delegates { 2 struct Currency { 3 public uint Dollars; 4 public ushort Cents; 5 6 public Currency(uint dollars, ushort cents) { 7 this.Dollars = dollars; 8 this.Cents = cents; 9 }10 11 public override string ToString() {12 return string.Format("${0}.{1,-2:00}", Dollars, Cents);13 }14 15 public static string GetCurrencyUnit() {16 return "Dollar";17 }18 19 public static explicit operator Currency(float value) {20 checked {21 uint dollars = (uint)value;22 ushort cents = (ushort)((value - dollars) * 100);23 return new Currency(dollars, cents);24 }25 }26 27 public static implicit operator float(Currency value) {28 return value.Dollars + (value.Cents / 100.0f);29 }30 31 public static implicit operator Currency(uint value) {32 return new Currency(value, 0);33 }34 35 public static implicit operator uint(Currency value) {36 return value.Dollars;37 }38 }39 40 }
在住函数中调用:
1 using System; 2 3 namespace Wrox.ProCSharp.Delegates 4 { 5 class Program 6 { 7 private delegate string GetAString(); 8 9 static void Main()10 {11 int x = 40;12 GetAString firstStringMethod = x.ToString;13 Console.WriteLine("String is {0}", firstStringMethod());14 15 Currency balance = new Currency(34, 50);16 17 // firstStringMethod references an instance method18 firstStringMethod = balance.ToString;19 Console.WriteLine("String is {0}", firstStringMethod());20 21 // firstStringMethod references a static method22 firstStringMethod = new GetAString(Currency.GetCurrencyUnit);23 Console.WriteLine("String is {0}", firstStringMethod());24 25 }26 }27 }
输出:
String is 40String is $34.50String is Dollar
委托的使用 - 浅谈
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。