许多情况下只有一个处理程序

问题描述

| 我有一个班级有2个实例。
Rectangle first = new Rectangle();
OnErrorHandler handler = new OnErrorHandler(Rectangle_OnError);
first.OnError += handler;
second.OnError += handler;

first.Width = 10;
first.Height = -5;

second.Width = -4;
second.Height = 2;

first.OnError -= handler;
first.Width = -1;
Rectangle second = new Rectangle();
我想知道哪个实例创建了事件?
namespace EventSample
{
    public delegate void OnErrorHandler(string message);    
}

public class Rectangle
{
    public event OnErrorHandler OnError;

    private int _Width;
    private int _Height;

    public int Width
    {
        get
        {
            return _Width;
        }
        set
        {
            if (value < 0)
            {
                if (OnError != null)
                    OnError(\"Width can not be less than zero!\");

                return;
            }

            _Width = value;
        }
    }
谢谢你的帮助。     

解决方法

        正如ChaosPandion所说的那样,您应该使用异常来告知错误情况。 假设您仍要使用事件,则应该对C#中的事件处理程序使用正确的约定。这涉及使用预定义的“ 2”委托,而不是创建自己的委托。签名是这样的:
public delegate void EventHandler<TEventArgs>(object sender,TEventArgs e);
在这种情况下,重要的部分是“ 4”,按照惯例,它是引发事件的实例。引发事件的典型方式是这样的:
EventHandler<MyEventArgs> myEvent = this.MyEvent;
if (myEvent != null)
{
    // pass \'this\' as sender to tell who is raising the event
    myEvent(this,new MyEventArgs(/* ... */));
}
    ,        您应该为此使用异常(如Chaos所述)。
if (value < 0)
{
  throw new ArgumentException(\"Width can not be less than zero!\");
}
参见MSDN