日常生活的交流与学习

首页 新随笔 联系 管理

# 委托类型 事件触发 回调函数 按钮事件

DelegateButton\DelegateButton.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

DelegateButton\Program.cs


public delegate void ButtonClickDelegate(object sender, EventArgs e);

public class Button
{
    public event ButtonClickDelegate OnClick;

    public void Click()
    {
        OnClick?.Invoke(this, EventArgs.Empty);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Button button = new Button();
        button.OnClick += Button_Click;
        button.Click();
    }

    private static void Button_Click(object sender, EventArgs e)
    {
        Console.WriteLine("Button was clicked!");
    }
}



posted on 2024-08-31 11:57  lazycookie  阅读(7)  评论(0编辑  收藏  举报