簡體   English   中英

C#4:在靜態克隆之間提升和訂閱事件

[英]C# 4: Raising and Subscribing Events Between Static CLasses

我花了最近幾天閱讀我的各種書籍並查看MSDN的文檔,我無法獲得看起來非常簡單的任務。

這就是我想要做的事情:我有一個靜態類,DBToolBox在SQL數據庫上運行各種函數,我希望它有一個獨立於UI的錯誤報告系統。 我想使用一個事件來指示日志(一個DataTable)是否已被更新,以便另一個靜態類(一個帶有DataGridView的窗體)將自行刷新。 這是我無法工作的代碼:

信號類:

public static class DBTools
{
public static readonly DataTable ErrorLog = new DataTable();
public static event EventHandler LogUpdated = delegate {};
// the actual functionality of the class

    private static void Error(Exception Ex, string MethodName)  
    {


        ErrorLog.Rows.Add((); 
        //logs the error with a bunch of data that I'm not listing here 

        LogUpdated(null, EventArgs.Empty); //I attempt to raise an event


    }

 }

反應類:

public static partial class ErrorWindow : Form
{

    DBToolbox.LogUpdated += ErrorWindow.ErrorResponse; 
    \\the offending event handler:
             \\invalid token "+=" in class, struct, or interface member declaration
             \\invalid token ";" in class, struct, or interface member declaration
             \\'QueryHelper_2._0.DBToolbox.LogUpdated' is a 'field' but is used like a 'type'
             \\'QueryHelper_2._0.ErrorWindow.ErrorResponse(object)' is a 'method' but is used like a 'type'



      private void Error_Load(object sender, EventArgs e)
    {
        ErrorLogView.DataSource = DBToolbox.ErrorLog;

    }

    public void ErrorResponse(object sender)
    {
        this.Show();
        this.ErrorLogView.DataSource = DBToolbox.ErrorLog;
        this.ErrorLogView.Refresh();
        this.Refresh();
    }

}

}

我究竟做錯了什么?

此外,還有另外兩個解決方案可以做我正在尋找的東西:第一個是DataTable自己的事件RowUpdated或NewTableRow,但我不知道如何加入該事件。

另一個是DataGridVeiw的DataSourceChanged事件,但我不知道這是否意味着當DataSource的地址發生變化時事件會發生,如果它的值發生變化。

我也在我的C#職業生涯中大約一個半星期,但在此之前我用VB2010編程了大約一年,所以我對.NET 4的函數庫有點熟悉。

這條線

DBToolbox.LogUpdated += ErrorWindow.ErrorResponse;

需要在一個方法中。 嘗試向包含該行的ErrorWindow添加靜態構造函數。

static ErrorWindow()
{
  DBToolbox.LogUpdated += ErrorWindow.ErrorResponse;
}

首先要做的事情是:如果所有部件都是這樣聲明的,則partial類只是靜態的。 另外(據我所知,因為我目前沒有辦法測試它) static類既不能繼承,也不能繼承另一個類。
最后但並非最不重要:UI元素衍生產品總是需要實例化的類,因為所有底層的東西都是基於實例的。

要將事件處理程序附加到事件,您需要在方法體內(即在構造函數中)執行此操作:

public ErrorWindow()
{
    InitializeComponent(); // Needed to init Winforms stuff
    DBToolbox.LogUpdated += ErrorResponse;
}

此外,您必須更改ErrorResponse事件處理程序以匹配void EventHandler(object, EventArgs)簽名。

設置DataSource后嘗試this.ErrorLogView.DataBind()

暫無
暫無

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

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