C#静态事件未触发

时间:2013-02-24 12:15:45

标签: c# events static null

我正在进行某种状态报告,因此我可以将新状态更新为UI。对于例如状态可以是 - “正在加载......”,“已加载......”等。我的问题是StatusChanged事件始终为null并且无法触发。

public class StatusReporter
{
    public delegate void StatusChangedEventHandler(Status status);

    public static event StatusChangedEventHandler StatusChanged;

    private static Status status;

    public static Status CurrentStatus
    {
        get
        {
            return status;
        }
        set
        {
            status = value;
            OnStatusChange();
        }
    }

    private static void OnStatusChange()
    {
        if (StatusChanged != null)
        {
            StatusChanged(status);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

代码:

public class StatusReporter {
    public delegate void StatusChangedEventHandler(Status status);
    public static event StatusChangedEventHandler StatusChanged;

    public static Status CurrentStatus {
        set {
            StatusReporter.OnStatusChange(status=value);
        }

        get {
            return StatusReporter.status;
        }
    }

    static void OnStatusChange(Status status) {
        if(null!=StatusChanged)
            StatusReporter.StatusChanged(status);
    }

    static Status status;
}

测试:

partial class Form1 {
    static void Form1_StatusChange(Status status) {
        Debug.Print("status changed");
    }

    private void button2_Click(object sender, EventArgs e) {
        StatusReporter.StatusChanged+=Form1_StatusChange;
        StatusReporter.CurrentStatus=new Status(); // assumed, you don't show the Status class
    }
}

虽然我不明白为什么所有静态