C#4:提高和订阅静态CLasses之间的事件

C#4:提高和订阅静态CLasses之间的事件

问题描述:

我花了几天的时间阅读我的各种书籍,并浏览了MSDN的文档,我无法得到看起来像是一项极其简单的工作。C#4:提高和订阅静态CLasses之间的事件

以下是我想要做的简单介绍:我有一个静态类,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的函数库略微熟悉。

首先第一件事情:partial类仅静若所有部分被宣布为。另外(据我所知,因为我目前没有办法测试它)static类既不能被继承,也不能继承另一个类。
最后但并非最不重要:UI元素衍生物总是需要实例化的类,因为所有基础的东西都是基于实例的。

和你的事件处理程序附加到事件中,你需要做这样的方法体内(即在构造函数):

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

另外,你不得不改变ErrorResponse事件处理程序相匹配void EventHandler(object, EventArgs)签名。

+0

是的!我试了一下,用它修改了一会儿,它就可以工作。这是如此美丽,我可以哭泣。 – Richard 2012-02-06 04:33:15

尝试this.ErrorLogView.DataBind()设置数据源后。

线

DBToolbox.LogUpdated += ErrorWindow.ErrorResponse; 

需要处于的方法。尝试添加一个静态构造函数给包含该行的ErrorWindow。

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

+1,因为我没有注意到当我阅读该问题时该行不在方法内。 – 2012-02-05 23:32:40