我的代码的目的是更改我的“ dispatcher”对象的名称,尽管这是通过调度程序的name属性的setter完成的,但它在引发事件的地方运行OnNameChange()。
这是我要在其中显示消息的地方运行“ OnDispatcherNameChange”方法的地方(“ Dispatcher的名称更改为”)。
但是,当我运行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;
}
}
}
}
答案 0 :(得分:3)
Name属性是问题所在。您有一个无限循环,在该循环中,setter再次调用该属性以设置另一个值。
将其更改为使用后备字段:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
var nameChange = new NameChangeEventArgs(Name);
OnNameChange(nameChange);
_name = value;
}
}