C#中的匿名方法如何使用?用法示例

2021年3月25日13:18:11 发表评论 895 次浏览

匿名方法是不包含任何名称的方法C#2.0。当用户想要创建一个内联方法并且还希望像其他方法一样在匿名方法中传递参数时, 此方法很有用。匿名方法是使用代表关键字, 用户可以将此方法分配给委托类型的变量。

语法如下:

delegate(parameter_list){
    // Code..
};

范例:

// C# program to illustrate how to 
// create an anonymous function
using System;
  
class GFG {
  
     public delegate void petanim( string pet);
  
     // Main method
     static public void Main()
     {
  
         // An anonymous method with one parameter
         petanim p = delegate ( string mypet)
         {
             Console.WriteLine( "My favorite pet is: {0}" , mypet);
         };
         p( "Dog" );
     }
}

输出如下:

My favorite pet is: Dog

重要事项:

此方法也称为

内联代表

.

使用此方法, 可以创建委托对象, 而无需编写单独的方法。

该方法可以访问外部方法中存在的变量。这种类型的变量称为

外部变量

。如下例所示, fav是外部变量。

例子:

// C# program to illustrate how an 
// anonymous function access variable
// defined in outer method
using System;
  
class GFG {
  
     // Create a delegate
     public delegate void petanim( string pet);
  
     // Main method
     static public void Main()
     {
  
         string fav = "Rabbit" ;
  
         // Anonymous method with one parameter
         petanim p = delegate ( string mypet)
         {
             Console.WriteLine( "My favorite pet is {0}." , mypet);
  
             // Accessing variable defined
             // outside the anonymous function
             Console.WriteLine( "And I like {0} also." , fav);
         };
         p( "Dog" );
     }
}

输出如下:

My favorite pet is Dog.
And I like Rabbit also.

你可以将此方法传递给另一个接受委托作为参数的方法。如下例所示:

范例:

// C# program to illustrate how an 
// anonymous method passed as a parameter
using System;
  
public delegate void Show( string x);
  
class GFG {
  
     // identity method with two parameters
     public static void identity(Show mypet, string color)
     {
         color = " Black" + color;
         mypet(color);
     }
  
     // Main method
     static public void Main()
     {
  
         // Here anonymous method pass as 
         // a parameter in identity method
         identity( delegate ( string color) { 
            Console.WriteLine( "The color" +
            " of my dog is {0}" , color); }, "White" );
     }
}

输出如下:

The color of my dog is  BlackWhite

在匿名方法中, 允许删除参数列表, 这意味着你可以将匿名方法转换为委托。

匿名方法块表示匿名方法中参数的范围。

匿名方法不包含跳转语句, 如goto, break或Continue。

匿名方法不会访问不安全的代码。

匿名方法不访问外部范围的in, ref和out参数。

你不能在is运算符的左侧使用匿名方法。

你还可以使用匿名方法作为事件处理程序。

例子:

// C# program to illustrate how an 
// anonymous method use as a 
// event handler
MyButton.Click += delegate (Object obj, EventArgs ev)
{
     System.Windows.Forms.MessageBox.Show( "Complete without error...!!" );
}

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: