我将在开始时指出,我只是在学习C#和事件。
我有这个程序的主Main类,它也创建了一个Form。在那个类中,我创建了a类的对象
在类B中,我定义了一个Event,我想让EventHandler从Main类订阅它(目的是在TextBox中显示从Event传递的文本(。怎么做?
在关于事件的教程中,通常显示了两个类的示例,在一个类中,从第二个类创建了一个对象,例如,在类级别A中为类B的对象订阅的事件如下所示:b.OnMultipleOfFiveReached += b_MultipleOfFiveReached;
我非常寻求帮助。
编辑:
表单类别:
using System;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
private ClassA _ClassAObject;
public Form1()
{
Console.WriteLine("Form!");
InitializeComponent();
_ClassAObject = new ClassA();
// It is IMPOSSIBLE to register Form handler to Class B event (no access to Class B object here):
//_ClassBObject.OnLogEntry += Form_OnLogEntryHandler;
}
public void Form_OnLogEntryHandler(object sender, LogEntryEventArgs e)
{
Console.WriteLine("Event Handler in Form! Log entry: " + e.LogEntry);
this.textBox1.Text = e.LogEntry;
}
}
}
A类:
using System;
namespace TestApp
{
public class ClassA
{
private ClassB _ClassBObject;
public ClassA()
{
Console.WriteLine("Class A Object!");
_ClassBObject = new ClassB();
// It is possible to register Class A handler to Class B event:
_ClassBObject.OnLogEntry += ClassA_OnLogEntryHandler;
_ClassBObject.StartProcess();
}
public void ClassA_OnLogEntryHandler(object sender, LogEntryEventArgs e)
{
Console.WriteLine("Event Handler in Class A object! Log entry: " + e.LogEntry);
}
}
}
B类:
using System;
namespace TestApp
{
public class ClassB
{
// declaring an event
public event EventHandler<LogEntryEventArgs> OnLogEntry;
public ClassB()
{
Console.WriteLine("Class B Object!");
}
public void StartProcess()
{
OnLogEntry?.Invoke(this, new LogEntryEventArgs("#1 Example Log Entry"));
}
}
public class LogEntryEventArgs : EventArgs
{
public LogEntryEventArgs(String iLogEntry)
{ LogEntry = iLogEntry; }
public String LogEntry { get; set; }
}
}
如果B的实例是由A公开的,例如,您有一个带有公共getter的MyB属性,而A是Main中的A var,那么您可以简单地编写a.MyB.OnMultipleOfFiveReached += b_MultipleOfFiveReached;
。
如果不是这样,并且类A中B的实例是私有的,则必须在A中定义另一个事件,该事件在B中的事件被触发时被触发。类似这样的东西:
public class B
{
public event EventHandler OnMultipleOfFiveReached;
}
public class A
{
private B b;
public event EventHandler OnMultipleOfFiveReachedInB;
public A()
{
b = new B();
b.OnMultipleOfFiveReached += B_OnMultipleOfFiveReached;
}
private void B_OnMultipleOfFiveReached(object sender, EventArgs e)
{
if (OnMultipleOfFiveReachedInB != null)
OnMultipleOfFiveReachedInB(sender, e);
}
}
此时,您可以在Main中编写a.OnMultipleOfFiveReachedInB += b_MultipleOfFiveReached;
。