Скажите, пожалуйста, в чем разница между Class1 и Class2 или между Event и Delegate?Я тестирую свой класс в Form1 и получаю тот же результат
// Class1.cs using System;using System.Collections.Generic;использование System.Linq;using System.Text;
class Class1EventArgs
{
public StringBuilder CallStack;
public Class1EventArgs() {
CallStack = new StringBuilder();
}
}
delegate void Class1EventHandler(Object sender, Class1EventArgs e);
class Class1
{
public event Class1EventHandler EventDelegate;
public void EventCaller()
{
Class1EventArgs e = new Class1EventArgs();
e.CallStack.AppendLine("EventCaller");
OnClass1Event(e);
}
protected virtual void OnClass1Event(Class1EventArgs e)
{
if (EventDelegate != null)
{
EventDelegate(this, e);
System.Windows.Forms.MessageBox.Show(e.CallStack.ToString());
}
}
}
// Class2.cs using System;using System.Collections.Generic;использование System.Linq;using System.Text;
public class Class2EventArgs
{
public StringBuilder CallStack = new StringBuilder();
}
public delegate void Class2EventHandler(object sender,Class2EventArgs e);
class Class2
{
public Class2EventHandler EventDelegate;
public Class2()
{
EventDelegate = new Class2EventHandler(this.OnEventHappen);
}
public void EventCaller()
{
Class2EventArgs e = new Class2EventArgs();
e.CallStack.AppendLine("EventCaller");
EventDelegate.Invoke(this, e);
System.Windows.Forms.MessageBox.Show(e.CallStack.ToString());
}
protected virtual void OnEventHappen(object sender, Class2EventArgs e)
{
e.CallStack.AppendLine("OnEventHappen");
}
}
// Form1.cs using System;using System.Collections.Generic;using System.ComponentModel;используя System.Data;использование System.Drawing;использование System.Linq;используя System.Text;используя System.Windows.Forms;
public partial class Form1 : Form
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
public Form1()
{
InitializeComponent();
}
#region "Button1"
private void button1_Click(object sender, EventArgs e)
{
c1.EventCaller();
}
private void c1_EvenDelegate(object sender, Class1EventArgs e)
{
e.CallStack.AppendLine("c1_EvenDelegate");
}
private void c1_EvenDelegate_2(object sender, Class1EventArgs e)
{
e.CallStack.AppendLine("c1_EvenDelegate_2");
}
#endregion
private void Form1_Load(object sender, EventArgs e)
{
//c1 = new Class1();
c1.EventDelegate += new Class1EventHandler(c1_EvenDelegate);
c1.EventDelegate += new Class1EventHandler(c1_EvenDelegate_2);
c2.EventDelegate += new Class2EventHandler(c2_OnEventHappen1);
c2.EventDelegate += new Class2EventHandler(c2_OnEventHappen2);
}
private void button2_Click(object sender, EventArgs e)
{
c2.EventCaller();
}
private void c2_OnEventHappen1(object sender, Class2EventArgs e)
{
e.CallStack.AppendLine("c2_OnEventHappen1");
}
private void c2_OnEventHappen2(object sender, Class2EventArgs e)
{
e.CallStack.AppendLine("c2_OnEventHappen2");
}
}