组播代理必须具有void的返回类型。为什么? [英] Multicast Delegates must have a return type of void. Why?
问题描述
我想知道背后的原因是什么,如果多个方法可以与代理人相同的返回类型?
前提是错误的;它工作正常:
Func< int> func = delegate {Console.WriteLine(first part);返回5; };
func + = delegate {Console.WriteLine(second part);返回7; };
int result = func();
这是一个具有非void结果的多播委托,工作正常。您可以从控制台看到两个部分都执行。最后一个项目的结果是返回的结果。我们可以证明这是一个真正的多播委托:
if(func是MulticastDelegate)Console.WriteLine(我是多播);
即使在第一行之后,它也会写我是多播 em>(当只列出一种方法时)
如果您需要对单个结果的更多控制,请使用 GetInvocationList()
:
foreach(Func< int> part in func.GetInvocationList())
{
int result = part();
}
可让您查看每个单独的结果。
在IL术语中:
.class public auto ansi sealed Func< + TResult>
扩展System.MulticastDelegate`
这就是说: Func< ; T>
继承自 MulticastDelegate
。基本上,对于所有意图和目的,.NET中的所有代表都是多播代理。您可以可以在托管C ++中获取非多播委托,我不知道。但肯定不是从C#。
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();
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).
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.
In IL terminology:
.class public auto ansi sealed Func<+ TResult>
extends System.MulticastDelegate`
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的返回类型。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!