簡體   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