[Windows Phone] Lambda 運算式(Lambda Expression)

本篇文章簡單的介紹以 Lambda 運算式(Lambda Expression)簡化方法的宣告。

前言

本篇文章簡單的介紹以 Lambda 運算式(Lambda Expression)簡化方法的宣告。

 

示範

Step1、建立一個新專案

01

 

Step2、畫面設計

在 Grid 內佈置下面畫面,其控制項配置如下:

  • Button 按鈕,Name 屬性:btn1,Content 屬性:6 的平方

02

 

產生的 XAML 程式碼如下:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button x:Name="bt1" Content="6的平方" HorizontalAlignment="Left" Margin="106,105,0,0" VerticalAlignment="Top" Height="110" Width="238" FontSize="36"/>
</Grid>

 

Step3、在 MainPage.cs 程式碼中撰寫事件處理函式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp1.Resources;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 建構函式
        public MainPage()
        {
            InitializeComponent();

            bt1.Click += bt1_Click; //產生btn1的Click事件
          
        }

        delegate int methAddr(int i);
        void bt1_Click(object sender, RoutedEventArgs e)
        {
            methAddr compSqu = x => x * x;
            int s = compSqu(6);
            MessageBox.Show("6的平方" + s.ToString());
        }
    }
}

 

結果

按一下頁面中的 Button。

03

 

就會顯示 6 的平方等於多少。

04

 

相關參考與引用

Lambda 運算式 (C# 程式設計手冊)