.net 2.0中的委托实例讲解

来源:这里教程网 时间:2026-02-21 14:53:16 作者:

  由于.net 2.0引入了匿名方法,所以创建委托的方式可以更简化了。

.net 2.0中的委托

有了匿名方法,上一篇的例子可以简化为:

 1 namespace DelegateDemo 2 
 { 3     //声明委托 4     
 public delegate void MyDel(string arg1, string arg2);
  5  6     class Program 7     
  { 8         static void Main(string[] args) 9         
  {10             //.net 2.0中的委托11 12           
   //创建委托,使用匿名方法13          
       MyDel myDel = delegate(string arg1, string arg2)14             
       {15               
         Console.WriteLine(string.Format("arg1:{0},arg2:{1}", arg1, arg2));16            
          };17 18             //调用委托19             myDel("aaa", "bbb");
          20 21             Console.ReadKey();
          22         
          }
          23     
          }
          24
           }

 

可以看到,不要再去单独定义类型和方法了,只需要使用内联的语法实现就可以了。

相关推荐