如何将Lambda Expression用作String参数C#

时间:2015-10-06 15:52:04

标签: c# string lambda delegates messagebox

只是出于好奇,我想知道是否可以将Lambda Expression用作String参数?

这是我的snipet:

List<Int64> selectedUsers = GetSelectedUsers();
if (MessageBox.Show(this, ((String message) =>
{
    message = "Are you sure you want to delete user(s) ID";
    foreach (Int64 id in selectedUsers)
    {
        message += " " + id.ToString();
    }
    message += "?";
    return message;
}), "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{ 
    //DoSomething();
}

但遗憾的是,我收到此错误“错误7无法将lambda表达式转换为类型'字符串',因为它不是委托类型”这里:(字符串消息)

感谢您的帮助,非常感谢!

3 个答案:

答案 0 :(得分:3)

之前构建您的消息
class Base
{ 
    public : 
        Base() { /*...*/}
        Base(const Base& other){/*...*/}
        virtual ~Base() {/*...*/}  
    private:
        /*...*/
};

class Derived : public Base
{ 
    public : 
        Derived() {/*...*/} 
        ~Derived() {/*...*/} 
        Derived(const Base& other) : Base(other){/*...*/}

};

int main()
{
    Base b;
    Derived d(b);
}

答案 1 :(得分:1)

如果 真的 想要使用某种代理来返回一个字符串(我老实说你不确定为什么会这样),你需要将表达式强制转换为Func<string>并立即调用它。

if (MessageBox.Show(this, 
    ((Func<string>)(() =>
        {
            var message = "Are you sure you want to delete user(s) ID";
            foreach (Int64 id in selectedUsers)
            {
                message += " " + id.ToString();
            }
            message += "?";
            return message;
       })
    )(), 
    "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    { 
        //DoSomething();
    }
}

答案 2 :(得分:0)

我认为这就是你应该做的事情

List<Int64> selectedUsers = GetSelectedUsers();

            if (MessageBox.Show(this, ((Func<string, string>)(message =>
            {
                message = "Are you sure you want to delete user(s) ID";
                foreach (Int64 id in selectedUsers)
                {
                    message += " " + id.ToString();
                }
                message += "?";
                return message;
            }))(""), "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                //DoSomething();
            }
        }

我们这里有一个IFFE。作为优化,你可以摆脱消息参数,因为你并没有真正使用初始值。这将成为:

List<Int64> selectedUsers = GetSelectedUsers();

            if (MessageBox.Show(this, ((Func<string>)(() =>
            {
                var message = "Are you sure you want to delete user(s) ID";
                foreach (Int64 id in selectedUsers)
                {
                    message += " " + id.ToString();
                }
                message += "?";
                return message;
            }))(), "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                //DoSomething();
            }

我希望这会有所帮助