繁体   English   中英

C#内联Lambda表达式

[英]C# inline lambda expression

标题很拗口,甚至不知道它的准确的(不能做的多大意义这个 ),所以我会尽力解释想我在完成C#使用等效javascript 关于我应该给这个问题加上什么标题的任何建议都非常欢迎。
C# ,说我已经定义了此函数:

Func<string, string> getKey = entity => {
    switch(entity) {
        case "a":
            return "foo";
        case "b":
            return "bar";
        default:
            return "baz";
    }
};

string key = getKey(/* "a", "b", or something else */);

现在假设我不想显式定义getKey函数,而是像在此等效的javascript代码段中那样匿名使用它:

string key = (function(entity) {
    switch(entity) {
        case "a":
            return "foo";
        case "b":
            return "bar";
        default:
            return "baz";
    }
}(/* "a", "b", or something else */));

我将如何使用C#编写代码? 我试过了:

string key = (entity => {
    switch(entity) {
        case "a":
            return "foo";
        case "b":
            return "bar";
        default:
            return "baz";
    }
})(/* "a", "b", or something else */);

但出现语法错误CS0149: Method name expected
在此先感谢您的欢呼。

IMO,最接近的等效项是:

var key = new Func<string, string>(entity =>
{
    switch (entity)
    {
        case "a":
            return "foo";
        case "b":
            return "bar";
        default:
            return "baz";
    }
})("a");

C#是一种编译语言,因此在很多方面与javascript不同。 您正在寻找的是闭包https://en.wikipedia.org/wiki/Closure_(computer_programming) 这些在C#中是可能的(例如Linq)。

但我认为,您所寻找的内容可以通过扩展方法( https://msdn.microsoft.com/zh-cn//library/bb383977.aspx )很好地解决:

using ExtensionMethods;
using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("a".ConvertKey());
        }
    }
}

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static string ConvertKey(this String key)
        {
            switch (key)
            {
                case "a":
                    return "foo";
                case "b":
                    return "bar";
                default:
                    return "baz";
            }
        }
    }
}

编辑:使用Linq的相同程序:

using System;
using System.Linq;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new[] { "a" }.Select(entity =>
            {
                switch (entity)
                {
                    case "a":
                        return "foo";
                    case "b":
                        return "bar";
                    default:
                        return "baz";
                }
            }).First());
            Console.ReadKey();
        }
    }
}

您可以将“选择”视为功能上的“地图”。 希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM