Multicast Delegates must have a return type of void. Why?(多播委托的返回类型必须为 void.为什么?)
问题描述
Multicast Delegates 的返回类型必须为 void,否则会抛出异常.
Multicast Delegates must have a return type of void Otherwise it will throw an exception.
我想知道它背后的原因是什么,如果多个方法可以具有与委托相同的返回类型怎么办?
I want to know whats the reason behind it, what if multiple methods could have a same return type as of a delegate ?
推荐答案
前提错了;它工作正常:
The premise is wrong; it works fine:
Func<int> func = delegate { Console.WriteLine("first part"); return 5; };
func += delegate { Console.WriteLine("second part"); return 7; };
int result = func();
这是一个非空结果的多播委托,工作正常.您可以从控制台看到这两个部分都已执行.last 项的结果是返回的那个.我们可以证明这是一个真正的多播委托:
That is a multicast delegate with a non-void result, working fine. You can see from the console that both parts executed. The result of the last item is the one returned. We can demonstrate that this is a true multicast delegate:
if(func is MulticastDelegate) Console.WriteLine("I'm multicast");
它会写我在多播"即使在第一行之后(当只列出一个方法时).
and it will write "I'm multicast" even after just the first line (when there is only a single method listed).
如果您需要对单个结果进行更多控制,请使用 GetInvocationList()
:
If you need more control over individual results, then use GetInvocationList()
:
foreach (Func<int> part in func.GetInvocationList())
{
int result = part();
}
它允许您查看每个单独的结果.
which allows you to see each individual result.
在 IL 术语中:
.class public auto ansi sealed Func<+ TResult>
extends System.MulticastDelegate`
也就是说:Func
继承自MulticastDelegate
.基本上,就所有意图和目的而言,.NET 中的所有委托都是多播委托.您可能能够在托管 C++ 中获得非多播委托,我不知道.但肯定不是来自 C#.
which is to say: Func<T>
inherits from MulticastDelegate
. Basically, to all intents and purposes, all delegates in .NET are multicast delegates. You might be able to get a non-multicast delegate in managed C++, I don't know. But certainly not from C#.
这篇关于多播委托的返回类型必须为 void.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多播委托的返回类型必须为 void.为什么?
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01