§ ITPOW >> 文档 >> C#

C# 中 Action 和 Func

作者:vkvi 来源:ITPOW(原创) 日期:2022-5-4

Action 和 Func 有着比委托更简洁的代码。

你可以把 Action、Func 看作是无返回值、有返回值的方法类型。

Action 示例

Action act = () =>
{
	Response.Write("我是无参数的方法。");
};

Action<int> act2 = (m) =>
{
	Response.Write("我是有参数的方法,参数值是:" + m);
};

act();
act2(1);

Action 支持 0-16 个参数,比如 Action<int, string>。

Func 示例

Func<int> func = () =>
{
	return 2;
};

Func<int, int> func2 = (m) =>
{
	return m * 2;
};

Response.Write(func()); // 2
Response.Write(func2(2)); // 4

Func 支持 0-16 个参数,最后一个泛型元素是返回值类型。

为什么需要 Action、Func?

上述示例,似乎看不出 Action、Func 有什么用,为何不直接用方法?

其实,某些场景还是有用的:比如我想把方法作为参数来传递时,就需要

private int Cal1(int m)
{
	return m * 2;
}


private int Cal2(int m)
{
	return m / 2;
}


private int Cal(Func<int, int> cal)
{
	return cal(2);
}


protected void Page_Load(object sender, EventArgs e)
{
	Response.Write(Cal(Cal1)); // 4
	Response.Write(Cal(Cal2)); // 1
}

相关阅读


相关文章