C#内联lambda表达式

时间:2016-04-08 09:31:56

标签: javascript c#

标题是满口的,甚至不确定它是否准确(对this没有多大意义),所以我将尝试通过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 提前谢谢,欢呼。

2 个答案:

答案 0 :(得分:6)

IMO,最接近的是:

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

答案 1 :(得分:0)

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

但我认为您正在寻找的内容可以通过扩展方法(https://msdn.microsoft.com/en-us//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();
        }
    }
}

您可以将“选择”视为功能性术语中的“地图”。希望这有帮助!

相关问题