我的代码的目的是更改我的“调度程序”对象的名称,虽然这是通过调度程序的名称属性的设置器完成的,但它在我引发事件的地方运行 OnNameChange() 。
这是我希望“OnDispatcherNameChange”方法在显示消息(“Dispatcher's name changed to”)的地方运行的地方。
但是,当我运行 main 并输入名称时,它会返回 StackOverFlowException。我怎样才能解决这个问题?
这是我的代码:
using System;
namespace Excercise_Events
{
public class NameChangeEventArgs : EventArgs
{
public string Name { get; private set; }
public NameChangeEventArgs(string name)
{
this.Name = name;
}
}
public class Dispatcher
{
public string Name
{
get
{
return Name;
}
set
{
var nameChange = new NameChangeEventArgs(Name);
OnNameChange(nameChange);
Name = value;
}
}
public delegate void NameChangeEventHandler(object Source, NameChangeEventArgs args);
public event NameChangeEventHandler NameChange;
protected virtual void OnNameChange(NameChangeEventArgs args)
{
NameChange?.Invoke(this, new NameChangeEventArgs(args.Name));
}
}
public class Handler
{
public void OnDispatcherNameChange(object Source, NameChangeEventArgs args)
{
Console.WriteLine("Dispatcher's name changed to {0}", args.Name);
}
}
class Program
{
static void Main(string[] args)
{
var dispatcher = new Dispatcher();
var handler = new Handler();
dispatcher.NameChange += handler.OnDispatcherNameChange;
while (true)
{
Console.Write("Enter new Name: ");
string name = Console.ReadLine();
if (name.ToLower() == "end")
{
break;
}
dispatcher.Name = name;
}
}
}
}
慕标琳琳
相关分类