如何使用 Lambda 表达式作为字符串参数 C#

How to use Lambda Expression as a String parameter C#

出于好奇,我想知道是否可以使用 Lambda 表达式作为字符串参数?

这是我的代码片段:

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

但不幸的是,我在此处收到此错误 "Error 7 Cannot convert lambda expression to type 'string' because it is not a delegate type":(字符串消息)

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

之前构建您的消息

string ids = selectedUsers.Select(n=>n.ToString()).Aggregate((current, next) => current + ", " + next);
// also works string.Join
// string ids = string.Join(", ",selectedUsers);
string message = "Are you sure you want to delete user(s) ID: "+ids+"?";
if (MessageBox.Show(this, message, "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{ 
    //DoSomething();
}

如果你真的想要使用某种委托来return一个字符串(老实说,我不知道你为什么会在这里),你需要将表达式转换为 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();
    }
}

我认为这是你应该做的

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。作为一种优化,您可以去掉 message 参数,因为您并没有真正使用初始值。这将变成:

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

希望对您有所帮助