匿名方法是不包含任何名称的方法C#2.0。当用户想要创建一个内联方法并且还希望像其他方法一样在匿名方法中传递参数时, 此方法很有用。匿名方法是使用代表关键字, 用户可以将此方法分配给委托类型的变量。
【C#中的匿名方法如何使用(用法示例)】语法如下:
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 isBlackWhite
在匿名方法中, 允许删除参数列表, 这意味着你可以将匿名方法转换为委托。
匿名方法块表示匿名方法中参数的范围。
匿名方法不包含跳转语句, 如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...!!" );
}
推荐阅读
- 操作系统试题和面试题分享|S3
- 编写一个函数,计算一个给定的int在链表中出现的次数
- 算法题(检查二叉树中的两个节点是否是表亲 |S2)
- 摩根大通(JP Morgan Chase)面试问题
- CSS表单和表单样式化用法详细指南
- Win8.1平板更新后续航时间变短的应对措施
- Win8设置PIN码时出现取得出错的处理办法
- 安装Win8.1时提示无法验证产品密钥怎样办?
- Win8升级Win8.1时提示无法更新保留分区怎样处理?