ZH TW CSharp Operator Lambda - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Lambda 表達式與主體表達式

使用手冊C# · 實用指南

聲明匿名函數或簡潔的表達式主體成員。如果可能的話,參數和結果類型是從上下文推斷出來的。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
System.Func<int, int> twice = value => value * 2;
System.Console.WriteLine(twice(4));

結果:

8

句法

value => expression / (left, right) => { ... }

範例1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Func<int, int> square = value => value * value;
        Console.WriteLine(square(4));
    }
}

範例2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        int offset = 3;
        Func<int, int> adjusted = value => { int result = value + offset; return result; };
        Console.WriteLine(adjusted(5));
    }
}

官方來源:Microsoft學習。

⚠️ **GitHub.com Fallback** ⚠️