Reputation: 151
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();
}
Upvotes: 5
Views: 8817
Reputation: 31404
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();
}
Upvotes: 0
Reputation: 9355
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());
Upvotes: 3