简体   繁体   中英

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); )

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 .

The example below will create add delegates to a that will call SomeFunc with the value of i at the time of the loop. 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#?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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