簡體   English   中英

C#當另一個類中的靜態方法被調用時,如何通知一個類(簡單的是/否)?

[英]C# How to notify a class (simple true/false) when a static method in another class has been invoked?

  • 題:

    ping運行后如何通知/更新Winform(這會改變我的假設發送指示器)?

  • 場景:

    假設我有關閉向計算機發送ping的線程。 當主線程顯示/負責winform gui時-完全獨立的類。

    1. 我有一個WinForm ,它顯示兩個小狀態指示器(發送和接收)
    2. 我有一個具有靜態方法Ping() B
    3. 我有一個連續運行Ping()的線程生成器

您最好使用“事件”,看看微軟提供的示例代碼, http://msdn.microsoft.com/en-us/library/aa645739( v = vs.71) .aspx

正如這里大多數人建議使用事件來做到這一點。

public partial class Form1: Form {
    public Form1() {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e) {
        Sample sample=new Sample();
        sample.SampleEvent+=sample_SampleEvent;
        sample.SampleMethod();
    }

    private void sample_SampleEvent() {
        Console.WriteLine("SampleMethod has been executed and the method on the WinForm has been notified about it.");
    }
}

public class Sample {
    public event SampleEventHandle SampleEvent;
    protected virtual void OnSampleEvent() {
        var handler=SampleEvent;
        if(handler!=null)
            handler();
    }

    public delegate void SampleEventHandle();


    public void SampleMethod() {
        OnSampleEvent();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM