2010-02-02 46 views
0

VS2008,C#,.NET FRAMEWORK2.0C#.net framework2.0如何動態分配方法事件

我想這一點:單擊button,webbrowser1._DocumentCompleted()事件撤銷DOA();點擊button2,它撤銷doB();點擊button3,它撤銷doC()。

我知道如何使用JAVA做到這一點,我猜C#也有這種機制。任何人都可以給我一些想法或更好的,給我看一些例子?

+1

做喲你的意思是「援引」? – womp 2010-02-02 20:10:52

回答

0

要添加到這些問題的答案,你還可以添加一個匿名方法的事件:

myButton.Click += (object sender, EventArgs e) => { 
    MessageBox.Show("MASSIVE ERROR!"); 
}; 

這意味着,你可以有效地調用一個方法,即使它不匹配相應的事件處理程序簽名:

myButton.Click += (object sender, EventArgs e) => { 
    DoA(); 
}; 

或(不使用蘭巴表達式):

myButton.Click += delegate(object sender, EventArgs e) { 
    DoA(); 
}; 
+0

我想這不會與.Net 2.0一起工作..只要3.5+如果我沒有錯 – Juri 2010-02-02 20:21:59

+1

@Juri:它不是.NET的函數 - 匿名方法是C#3.0的一個功能,它無關緊要與.NET 3.0或.NET 3.5。您可以在.NET 2.0程序中使用C#3.0功能。 – 2010-02-02 20:26:05

+0

@Juri:如果您使用的是舊版本的C#,上面的代碼不會編譯;但是仍然可以使用匿名方法,只是使用不同的語法。 (看我的編輯。) – 2010-02-02 20:37:36

2
myButton.Click += myButton_Click; 

protected void myButton_Click(object sender, EventArgs e) {} 
0

如果你想添加事件處理程序的控制,這是我想你所描述,你可以很容易地做到這一點。一個常用的方法是在後面頁面加載分配在碼控制的事件處理程序:

protected void Page_Load(object sender, EventArgs e) 
{ 
    //add the event handler for the click event. You could provide other 
    //logic to determine dynamically if the handler should be added, etc. 
    btnButton1.Click += new EventHandler(btnButton1_Click); 
    btnButton2.Click += new EventHandler(btnButton2_Click); 
    btnButton3.Click += new EventHandler(btnButton3_Click); 
} 

protected void btnButton1_Click(object sender, EventArgs e) 
{ 
    //get the button, if you need to... 
    Button btnButton1 = (Button)sender; 

    //do some stuff... 
    DoA(); 
} 

protected void btnButton2_Click(object sender, EventArgs e) 
{  
    //do some stuff... 
    DoB(); 
} 

protected void btnButton3_Click(object sender, EventArgs e) 
{  
    //do some stuff... 
    DoC(); 
} 



private void DoA() {} 
private void DoB() {} 
private void DoC() {} 
1

添加處理程序

button.Click + = buttonClickEventHandler;

要刪除處理程序

button.Click - = buttonClickEventHandler;

0

聲明事件

public class MyClass1 
{ 
    ... 

    public event EventHandler<EventArgs> NotifyValidate; 
    protected void RaiseNotifyValidate(EventArgs e) 
    { 
     if (NotifyValidate != null) 
     { 
      NotifyValidate(this, e); 
     } 
    } 

    ... 
} 

觸發該事件在你的代碼

... 
RaiseNotifyValidate(new EventArgs()); //EventArgs could be more sophisticated, containing data etc.. 

註冊在你的代碼事件:

... 
MyClass aObj = new MyClass(); 
aObj.NotifyValidate += new EventHandler(onNotifyValidate); 
... 
private void onNotifyValidate(object sender, EventArgs e) 
{ 
    //do what you need to 
} 

正如丹指出,與Lambda表達式可以定義事件如

aObj.NotifyValidate += (s,ev) => 
    { 
     //handle your event 
    };