开发者

Action<T> vs anonymous method question

开发者 https://www.devze.com 2022-12-22 11:24 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消