c#匿名方法用途_C#匿名方法

本文介绍了C#语言中的匿名方法,它是一种将代码块作为委托参数传递的技术,无名称只有方法体,返回类型从return语句推断。还说明了使用delegate关键字创建代理实例时可声明匿名方法,并给出了编写示例及完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#语言 的 C#匿名方法

前面我们学习过,委托可用于引用任何与委托签名相同的方法。换句话说,可以调用可以由委托使用该委托对象引用的方法。

匿名方法提供了一种将代码块作为委托参数传递的技术。匿名方法是没有名称的方法,只有方法体。

不需要在匿名方法中指定返回类型; 它是从方法体中的return语句来推断的。

编写匿名方法

使用delegate关键字创建代理实例时,就可以声明匿名方法。 例如,

delegate void NumberChanger(int n);

...

NumberChanger nc = delegate(int x)

{

Console.WriteLine("Anonymous Method: {0}", x);

};

代码块Console.WriteLine("Anonymous Method: {0}", x);是匿名方法体。

代理可以使用匿名方法和命名方法以相同的方式调用,即通过将方法参数传递给委托对象。

例如,

nc(10);

示例

以下示例演示如何实现概念:

using System;

delegate void NumberChanger(int n);

namespace DelegateAppl

{

class TestDelegate

{

static int num = 10;

public static void AddNum(int p)

{

num += p;

Console.WriteLine("Named Method: {0}", num);

}

public static void MultNum(int q)

{

num *= q;

Console.WriteLine("Named Method: {0}", num);

}

public static int getNum()

{

return num;

}

static void Main(string[] args)

{

//create delegate instances using anonymous method

NumberChanger nc = delegate(int x)

{

Console.WriteLine("Anonymous Method: {0}", x);

};

//calling the delegate using the anonymous method

nc(10);

//instantiating the delegate using the named methods

nc = new NumberChanger(AddNum);

//calling the delegate using the named methods

nc(5);

//instantiating the delegate using another named methods

nc = new NumberChanger(MultNum);

//calling the delegate using the named methods

nc(2);

Console.ReadKey();

}

}

}

当上述代码被编译并执行时,它产生以下结果:

Anonymous Method: 10

Named Method: 15

Named Method: 30

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值