Func delegate doesn#39;t chain methods(Func 委托不链接方法)
问题描述
让我们想象一下简单的委托调用:
Lets imagine simple delegate calls:
void Main()
{
Func<int, int, string> tfunc = null;
tfunc += Add; // bind first method
tfunc += Sub; // bind second method
Console.WriteLine(tfunc(2, 2));
}
private string Add(int a, int b)
{
return "Add: " + (a + b).ToString();
}
private string Sub(int a, int b)
{
return "Sub: " + (a - b).ToString();
}
这个程序的结果是:
Sub: 0
那么,为什么没有调用 Add 方法呢?我期待调用方法 Add,然后 然后 方法 Sub.
So, why Add method was not called? I'm expecting to call Method Add, and then method Sub.
推荐答案
Add被正确链接调用,看看结果
Add was correctly chained and called, take a look at the result of
void Main()
{
Func<int, int, string> tfunc = null;
tfunc += Add; // bind first method
tfunc += Sub; // bind second method
Console.WriteLine(tfunc(2, 2));
}
private string Add(int a, int b)
{
Console.WriteLine("Inside Add");
return "Add: " + (a + b).ToString();
}
private string Sub(int a, int b)
{
Console.WriteLine("Inside Sub");
return "Sub: " + (a - b).ToString();
}
它是:
Inside Add
Inside Sub
Sub: 0
没有被链接,因为没有办法访问它,是 Add 方法的结果.返回值的委托,在链接的情况下,返回最后调用的方法的值,即添加到委托的最后一个方法.
What is not chained, because there is no way to access it, is the result of the Add method. Delegates that return a value, in case of chaining, return the value of the last method invoked, that is the last method that was added to the delegate.
这在 C# 4.0 语言规范 的第 15.4 部分中指定
This is specified in part 15.4 of the C# 4.0 language specification
调用一个委托实例,其调用列表包含多个条目通过调用调用列表,同步,按顺序....如果委托调用包含输出参数或返回值,它们的最终值将来自于列表中的最后一位代表.
Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. ... If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.
这篇关于Func 委托不链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Func 委托不链接方法
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
