C# lambda 表达式中的 switch

发布于 2024-08-04 11:16:40 字数 62 浏览 5 评论 0原文

是否可以在 lambda 表达式中添加 switch?如果没有,为什么? Resharper 将其显示为错误。

Is it possible to have a switch in a lambda expression? If not, why? Resharper displays it as an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

故事还在继续 2024-08-11 11:16:40

您可以在语句块中使用 lambda:

Action<int> action = x =>
{
  switch(x)
  {
    case 0: Console.WriteLine("0"); break;
    default: Console.WriteLine("Not 0"); break;
  }
};

但是您不能在“单个表达式 lambda”中执行此操作,因此这是无效的:

// This won't work
Expression<Func<int, int>> action = x =>
  switch(x)
  {
    case 0: return 0;
    default: return x + 1;
  };

这意味着您不能在表达式树中使用 switch(至少是由 C# 编译器生成的;我相信 .NET 4.0 至少在库中支持它)。

You can in a statement block lambda:

Action<int> action = x =>
{
  switch(x)
  {
    case 0: Console.WriteLine("0"); break;
    default: Console.WriteLine("Not 0"); break;
  }
};

But you can't do it in a "single expression lambda", so this is invalid:

// This won't work
Expression<Func<int, int>> action = x =>
  switch(x)
  {
    case 0: return 0;
    default: return x + 1;
  };

This means you can't use switch in an expression tree (at least as generated by the C# compiler; I believe .NET 4.0 at least has support for it in the libraries).

情释 2024-08-11 11:16:40

在纯表达式(在.NET 3.5中)中,您可以获得的最接近的是复合条件:

    Expression<Func<int, string>> func = x =>
        x == 1 ? "abc" : (
        x == 2 ? "def" : (
        x == 3 ? "ghi" :
                 "jkl")); /// yes, this is ugly as sin...

不好玩,尤其是当它变得复杂时。如果您指的是带有语句主体的 lamda 表达式(仅适用于 LINQ-to-Objects),那么大括号内的任何内容都是合法的:

    Func<int, string> func = x => {
        switch (x){
            case 1:  return "abc";
            case 2:  return "def";
            case 3:  return "ghi";
            default: return "jkl";
        }
    };

当然,您可以外包这项工作;例如,LINQ-to-SQL 允许您将标量 UDF(在数据库中)映射到数据上下文上的方法(实际未使用) - 例如:

var qry = from cust in ctx.Customers
          select new {cust.Name, CustomerType = ctx.MapType(cust.TypeFlag) };

其中 MapType 是在数据库服务器上执行工作的 UDF。

In a pure Expression (in .NET 3.5), the closest you can get is a compound conditional:

    Expression<Func<int, string>> func = x =>
        x == 1 ? "abc" : (
        x == 2 ? "def" : (
        x == 3 ? "ghi" :
                 "jkl")); /// yes, this is ugly as sin...

Not fun, especially when it gets complex. If you mean a lamda expression with a statement body (only for use with LINQ-to-Objects), then anything is legal inside the braces:

    Func<int, string> func = x => {
        switch (x){
            case 1:  return "abc";
            case 2:  return "def";
            case 3:  return "ghi";
            default: return "jkl";
        }
    };

Of course, you might be able to outsource the work; for example, LINQ-to-SQL allows you to map a scalar UDF (at the database) to a method on the data-context (that isn't actually used) - for example:

var qry = from cust in ctx.Customers
          select new {cust.Name, CustomerType = ctx.MapType(cust.TypeFlag) };

where MapType is a UDF that does the work at the db server.

-残月青衣踏尘吟 2024-08-11 11:16:40

是的,它可以工作,但是您必须将代码放在一个块中。示例:

private bool DoSomething(Func<string, bool> callback)
{
    return callback("FOO");
}

然后,调用它:

DoSomething(val =>
                {
                    switch (val)
                    {
                        case "Foo":
                            return true;

                        default:
                            return false;
                    }
                });

Yes, it works, but you have to put your code in a block. Example:

private bool DoSomething(Func<string, bool> callback)
{
    return callback("FOO");
}

Then, to call it:

DoSomething(val =>
                {
                    switch (val)
                    {
                        case "Foo":
                            return true;

                        default:
                            return false;
                    }
                });
燃情 2024-08-11 11:16:40

您可以在语句块 lambda 中:

public static string CarBrandIdNotExist(AppLanguage language) => language switch
    {
        AppLanguage.English => "CarBrandId not exist",
        AppLanguage.Arabic => "CarBrandId not exist",
        AppLanguage.India => "CarBrandId not exist",
        AppLanguage.Filipino => "CarBrandId not exist",
        _ => "CarBrandId not exist",
    };

You can in a statement block lambda:

public static string CarBrandIdNotExist(AppLanguage language) => language switch
    {
        AppLanguage.English => "CarBrandId not exist",
        AppLanguage.Arabic => "CarBrandId not exist",
        AppLanguage.India => "CarBrandId not exist",
        AppLanguage.Filipino => "CarBrandId not exist",
        _ => "CarBrandId not exist",
    };
风尘浪孓 2024-08-11 11:16:40

嗯,我认为这没有理由行不通。请注意您使用的语法

param => {
    // Nearly any code!
}

delegate (param) {
    // Nearly any code!
}

param => JustASingleExpression (No switches)

Hmm, I see no reason why this shouldn't work. Just be careful with the syntax you use

param => {
    // Nearly any code!
}

delegate (param) {
    // Nearly any code!
}

param => JustASingleExpression (No switches)
扛刀软妹 2024-08-11 11:16:40

我也检查了:-)

[Test]
public void SwitchInLambda()
{
    TakeALambda(i => {
        switch (i)
        {
            case 2:
                return "Smurf";
            default:
                return "Gnurf";
        }
    });
}

public void TakeALambda(Func<int, string> func)
{
    System.Diagnostics.Debug.WriteLine(func(2));
}

工作得很好(输出“Smurf”)!

I checked it too :-)

[Test]
public void SwitchInLambda()
{
    TakeALambda(i => {
        switch (i)
        {
            case 2:
                return "Smurf";
            default:
                return "Gnurf";
        }
    });
}

public void TakeALambda(Func<int, string> func)
{
    System.Diagnostics.Debug.WriteLine(func(2));
}

Works just fine (outputs "Smurf")!

本王不退位尔等都是臣 2024-08-11 11:16:40

输入图片这里的描述

我刚刚学到这个:

                      (model) =>
                                {
                                    switch(model.SentInvoiceTypeId)
                                    {
                                        case 1:
                                            return "1 asdf";
                                        case 2:
                                            return "2 asdf";
                                        case 3:
                                            return "3 asdf ";
                                        case 4:
                                            return "4 asdf ";
                                        default:
                                            return "asdf";
                                    }
                                }

只需放在“model”()之间并在{}中添加您的代码,记住有一个返回。
我不确定 C# 的哪个版本可以工作,在这个例子中是 C# 7.0

我希望这个答案可以帮助别人。

enter image description here

I just learn this:

                      (model) =>
                                {
                                    switch(model.SentInvoiceTypeId)
                                    {
                                        case 1:
                                            return "1 asdf";
                                        case 2:
                                            return "2 asdf";
                                        case 3:
                                            return "3 asdf ";
                                        case 4:
                                            return "4 asdf ";
                                        default:
                                            return "asdf";
                                    }
                                }

Just put between the "model" () and add your code in { }, remember to have a return.
I am not sure in which versions of C# will work, In this example is the C# 7.0

I hope this answer can help someone.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文