多播委托的返回类型必须为 void.为什么?

Multicast Delegates must have a return type of void. Why?(多播委托的返回类型必须为 void.为什么?)

本文介绍了多播委托的返回类型必须为 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.为什么?

基础教程推荐