简体   繁体   English

传递参数以委托c#

[英]Pass parameter to delegate c#

I have an issue that I wish to add function calls to a delegate, but each of these function calls will have a unique parameter. 我有一个问题,我希望将函数调用添加到委托,但每个函数调用将具有唯一的参数。 I cannot figure it out or find a solution elsewhere so I am turning to you guys :) 我无法弄清楚或在其他地方找到解决方案,所以我转向你们:)

Some pseudo below.. 一些假下面..

(So basically, I am creating a delegate and an event and the AddToDelegate function is supposed to add the function calls to the event (with a unique value), then the GetData function returns all the responses in one string - the problem comes in the AddToDelegate function as the line a += new A(SomeFunc)(i.ToString()); should really only be a += new A(SomeFunc); ) (所以基本上,我正在创建一个委托和一个事件,AddToDelegate函数应该添加对事件的函数调用(具有唯一值),然后GetData函数返回一个字符串中的所有响应 - 问题出现在AddToDelegate函数作为行a += new A(SomeFunc)(i.ToString());实际上应该只是一个+= new A(SomeFunc);

Is there a way to do this with delegates - or am I barking up the wrong tree? 有没有办法与代表这样做 - 或者我在咆哮错误的树?

public delegate string A(string s);
public event A a;

public void AddToDelegate()
{
    for (int i = 0; i < DelegateList.Length; i++)
    {
        a += new A(SomeFunc)(i.ToString());
    }
}

public string GetData()
{
    StringBuilder _sb = new StringBuilder();
    if (a != null)
    {
        Delegate[] DelegateList = a.GetInvocationList();
        for (int i = 0; i < DelegateList.Length; i++)
        {
            _sb.Append(((A)DelegateList[i]));
        }
    }
    return _sb.ToString();
}

Not sure what you really want, but you can use an anonymous function that will hold this extra variable inside its scope: 不确定你真正想要的是什么,但是你可以使用一个匿名函数将这个额外的变量保存在它的范围内:

a += new A( s => { 
    string extra_value = i.ToString();
    return SomeFunc(s, extra_value);
  });

Which can be simplified into this: 哪个可以简化为:

a += s => SomeFunc(s, i.ToString());

Yes you can do this via labda expressions and closures . 是的,你可以通过labda表达式闭包来做到这一点。

The example below will create add delegates to a that will call SomeFunc with the value of i at the time of the loop. 下面的示例将创建一个add委托给一个将在循环时调用SomeFunc的值为i。 The variable capture is needed to ensure that the correct value is captured - see How to tell a lambda function to capture a copy instead of a reference in C#? 需要变量capture以确保capture正确的值 - 请参阅如何告诉lambda函数捕获副本而不是C#中的引用?

public event Action<string> a;

public void AddToDelegate()
{
    for (int i = 0; i < DelegateList.Length; i++)
    {
        int capture = i;
        a += () => SomeFunc(capture.ToString());
    }
}

public string GetData()
{
    StringBuilder _sb = new StringBuilder();
    if (a != null)
    {
        Delegate[] DelegateList = a.GetInvocationList();
        for (int i = 0; i < DelegateList.Length; i++)
        {
            _sb.Append((Action<string>)DelegateList[i]());
        }
    }
    return _sb.ToString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM