c# - 获取委托(delegate)中所有返回的字符串表单方法

标签 c# delegates

我在这段代码中有一个关于委托(delegate)的问题,我添加了三个委托(delegate)方法。返回一个字符串。在行中

string delOut = del("Beer");

给我宝贵的 delOut 委托(delegate)分配这个“长度:4”

如何收集委托(delegate)方法返回的所有字符串?

public class NaForum
{
    public delegate string MyDelegate(string s);

    public void TestDel()
    {
        MyDelegate del = s => s.ToLower();
        del += s => s.ToUpper();
        del += s => string.Format("Length : {0}", s.Length);

        string delOut = del("Beer");
        Console.WriteLine(delOut);
    }
}

感谢您的回答。

最佳答案

您需要使用 Delegate.GetInvocationList :

var results = new List<string>();

foreach (MyDelegate f in del.GetInvocationList()) {
    results.Add(f("Beer"));
}

现在,results 包含所有返回值。

关于c# - 获取委托(delegate)中所有返回的字符串表单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17169821/

相关文章:

ios - 如何在 View Controller 之外设置数据源和委托(delegate)

c# - 在 C# 中从类型到接口(interface)的隐式转换——基本示例有效,但实际实现存在编译时错误

c# - C# 引用和指针有什么区别?

c# - 从 C# 编写 excel 的有效方法

c# - C# 的动态键是否弃用静态 IOC 模式?

.net - 让 IAsyncResult 触发 "completed"事件

c# - 在 Entity Framework 4.0 中显示 "Nested transactions are not supported"错误?

c# - 如果放弃 .NET 中的标准 EventHandler 模式,我会失去什么?

ios - 是否需要保留数据源的 Controller 和 uiPickerview 的委托(delegate)?

ios - UIWebview : How to notify UIViewController if any of the already loaded link in the web view fails to open