首頁 後端開發 C#.Net教程 c#如何在程式中定義和使用自訂事件

c#如何在程式中定義和使用自訂事件

Mar 09, 2019 pm 04:50 PM
自訂事件

C#在程式中定義並使用自訂事件的方法:先在類別中定義事件;然後定義事件的參數;接著在TestClass中來引發事件;最後使用事件即可。

c#如何在程式中定義和使用自訂事件

C#在程式中定義和使用自訂事件的步驟有:首先在類別中定義事件,然後再定義事件的參數,在TestClass中來引發事件最後使用事件

【推薦課程:C#教學

C#在程式中定義和使用自訂事件可以分為以下幾個步驟:

步驟1:在類別中定義事件

using System;
public class TestClass
{
    //....
    public event EventHandler TestEvent
}

步驟2:定義事件參數

注意:事件參數類別TestEventArgs繼承自System.EventArgs

using System;
public class TestEventArgs : EventArgs
{
    public TestEventArgs() : base() { }
 
    public string Message { get; set; }
}

步驟3:在TestClass 引發事件

public class TestClass
{
    // 这个方法引发事件
    public void RaiseTestEvent(string message)
    {
        if (TestEvent == null) return;
        TestEvent(this, new TestEventArgs { Message = message });
    }
    public event EventHandler TestEvent; 
}

步驟4:使用事件

#
class Program
{
    static void Main(string[] args)
    {
 
        TestClass tc = new TestClass();
        // 挂接事件处理方法
        tc.TestEvent += Tc_TestEvent;
         
        Console.WriteLine("按任意键引发事件");
        Console.ReadKey();        
        // 引发事件
        tc.RaiseTestEvent("通过事件参数传递的字符串");
         
        Console.WriteLine("按任意键退出");
        Console.ReadKey();
    }
    private static void Tc_TestEvent(object sender, EventArgs e)
    {
        // 将事件参数强制转换为TestEventArgs
        TestEventArgs te = (TestEventArgs)e;
        // 显示事件参数中的Message
        Console.WriteLine(te.Message);
    }
}

完整的程序如下

using System;
public class TestClass
{
    public void RaiseTestEvent(string message)
    {
        if (TestEvent == null) return;
        TestEvent(this, new TestEventArgs { Message = message });
    }
 
    public event EventHandler TestEvent; 
}
public class TestEventArgs : EventArgs
{
    public TestEventArgs() : base() { }
 
    public string Message { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
 
        TestClass tc = new TestClass();
        tc.TestEvent += Tc_TestEvent;
        Console.WriteLine("按任意键引发事件");
        Console.ReadKey();
        tc.RaiseTestEvent("通过事件参数传递的字符串");
        Console.WriteLine("按任意键退出");
        Console.ReadKey();
    }
    private static void Tc_TestEvent(object sender, EventArgs e)
    {
        TestEventArgs te = (TestEventArgs)e;
        Console.WriteLine(te.Message);
    }
}

總結:以上就是這篇文章的全部內容了,希望對大家有所幫助。

以上是c#如何在程式中定義和使用自訂事件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何從C#中讀取AppSettings.json的應用程序設置? 如何從C#中讀取AppSettings.json的應用程序設置? Sep 15, 2025 am 02:16 AM

答案是使用Microsoft.Extensions.Configuration讀取appsettings.json。 1.創建appsettings.json並設置複製屬性;2.安裝Microsoft.Extensions.Configuration.Json包;3.用ConfigurationBuilder加載配置;4.通過索引器或GetConnectionString讀取值;5.推薦使用強類型配置類Bind或Get綁定。

如何在C#中正確使用HTTPCLIENT類? 如何在C#中正確使用HTTPCLIENT類? Sep 15, 2025 am 01:23 AM

HttpClient應長期復用而非頻繁創建,推薦通過IHttpClientFactory注入管理,避免socket耗盡;若無DI則用靜態實例,確保生命週期合理。

C#字符串與StringBuilder的性能和用法。 C#字符串與StringBuilder的性能和用法。 Sep 16, 2025 am 05:24 AM

usestringforminimal,pattictextepterations; usestringbuilderforfrefrequentmodificationsinloopsorlarge-scaleconconcatenation stoImpReverPerformancanceanDrefformanceanDreduceMemoryallocation。

從整體到微服務:.NET應用程序的遷移指南 從整體到微服務:.NET應用程序的遷移指南 Sep 19, 2025 am 05:21 AM

遷移.NET單體應用到微服務應避免一次性重寫,1.首先明確遷移動機並規避常見陷阱,確保團隊具備DevOps與可觀測性能力;2.採用絞殺者模式逐步替換,通過API網關路由新功能至新服務;3.運用領域驅動設計識別限界上下文,按業務邊界拆分服務並隔離數據庫;4.選擇合適的通信方式,對用戶請求用HTTP/REST,對事件用異步消息如AzureServiceBus;5.通過事件最終一致性、Saga模式和Outbox模式保障跨服務數據一致性;6.早期集成Serilog、OpenTelemetry等工具構建日

c#linq中的first()和firstordefault()有什麼區別? c#linq中的first()和firstordefault()有什麼區別? Sep 16, 2025 am 12:33 AM

first()throwsAnexceptionifnoElementIffound,wherfirstordefault()returnSadeFaultValue; usefirst()whenthesequenceisexpectedTobenon-empty,andfirstordEfault()tohandleStordEft()

C#中有哪些不同的訪問修飾符? C#中有哪些不同的訪問修飾符? Sep 21, 2025 am 01:43 AM

public成員可被任意代碼訪問;2.private僅限類內訪問;3.protected允許類及派生類訪問;4.internal限同一程序集內訪問;5.protectedinternal為protected與internal的並集,用於派生類或同程序集訪問。

如何在C#中創建和使用ComellationToken? 如何在C#中創建和使用ComellationToken? Sep 21, 2025 am 01:49 AM

創建CancellationTokenSource獲取CancellationToken,用於通知其他線程或組件取消操作。 2.將令牌傳遞給支持取消的異步方法(如Task.Run),任務可週期性檢查取消請求,實現優雅終止。

如何在C#中使用模式匹配? 如何在C#中使用模式匹配? Sep 20, 2025 am 04:32 AM

PatternmatchinginC#isafeatureusedtocheckobjectsagainstpatternsandextractinformationconcisely.1.Typepatternsallowcheckingandcastinginonestep,asshownwithif(valueisstringstr).2.Constantpatternscomparevaluesagainstconstantsdirectly,suchascheckingif(input

See all articles