C# 4:在静态类之间引发和订阅事件

Ric*_*ard 5 c#

在过去的几天里,我阅读了各种书籍并浏览了 MSDN 的文档,但我无法完成看似极其简单的任务。

简而言之,我想要做的就是:我有一个静态类 DBToolBox,它在 SQL 数据库上运行各种函数,并且我希望它有一个独立于 UI 的错误报告系统。我想使用一个事件在日志(DataTable)更新时发出信号,以便另一个静态类(带有 DataGridView 的 Windows 窗体)将刷新自身。这是我无法工作的代码:

信令类:

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


    }

 }
Run Code Online (Sandbox Code Playgroud)

反应类:

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

}

我究竟做错了什么?

另外,还有另外两个解决方案可以完成我正在寻找的操作:第一个是 DataTable 自己的事件 RowUpdated 或 NewTableRow,但我不确定如何订阅该事件。

另一个是 DataGridVeiw 的 DataSourceChanged 事件,但我不知道这是否意味着当 DataSource 的地址更改时触发该事件,或者它的值是否更改。

我的 C# 职业生涯也刚刚开始一周半,但在此之前我使用 VB2010 进行了大约一年的编程,因此我对 .NET 4 的函数库有些熟悉。

Nuf*_*fin 1

首先要做的事情是:只有当所有部分都声明为partial静态时,类才是静态的。另外(据我所知,因为我目前没有办法测试它)类既不能被另一个类继承,也不能自己继承另一个类。 最后但并非最不重要的一点是:UI 元素派生始终需要实例化类,因为所有底层内容都是基于实例的。static

要将事件处理程序附加到事件,您需要在方法主体内(即在构造函数中)执行此操作:

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

此外,您还必须更改ErrorResponse事件处理程序以匹配void EventHandler(object, EventArgs)签名。