I had a question answered which raised another one, why following does not work? I do not understand it. The compiler says: Cannot convert anonymous method do string. But why?
public List<string> list = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
a.IterateObjects(B);
// why this does not work:
a.IterateObjects(delegate(string a) { listBox1.Items.Add(a); });
}
private void B(string a)
{
listBox1.Items.Add(a);
}
public void IterateObjects(Action<string> akce)
{
foreach (string a in list)
{
akce(a);
}
}
开发者_如何学运维
You have some variable confusion. a
is already declared elsewhere, so change:
a.IterateObjects(delegate(string a) { listBox1.Items.Add(a); });
to:
a.IterateObjects(delegate(string s) { listBox1.Items.Add(s); });
and it should work fine.
I think it's because ListBoxItemCollection.Add
actually returns an integer. So that would be a Func<string, int>
, not an Action<string>
.
EDIT: Never mind; I guess since you were using a delegate
statement you would have had to use return
for it to evaluate as a Func
-like object.
精彩评论