开发者

one handler for many instance

开发者 https://www.devze.com 2023-03-12 19:36 出处:网络
I have 2 instances from one class. Rectangle first = new Rectangle(); OnErrorHandler handler = new OnErrorHandler(Rectangle_OnError);

I have 2 instances from one class.

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();

and I want to know which instance creates event?

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)
            {
   开发者_JAVA百科             if (OnError != null)
                    OnError("Width can not be less than zero!");

                return;
            }

            _Width = value;
        }
    }

thanks for your help.


As ChaosPandion said above, you should use exceptions to inform about error conditions.

Assuming that you still want to use events, you should use the proper convention for event handlers in C#. This involves using the predefined EventHandler<TEventArgs> delegate rather than creating your own delegate. The signature is this:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The important part in this case is the sender, which by convention is the instance which raised the event. The typical way to raise the event is like this:

EventHandler<MyEventArgs> myEvent = this.MyEvent;
if (myEvent != null)
{
    // pass 'this' as sender to tell who is raising the event
    myEvent(this, new MyEventArgs(/* ... */));
}


You should be using exceptions for this (as Chaos mentions).

if (value < 0)
{
  throw new ArgumentException("Width can not be less than zero!");
}

see MSDN

0

精彩评论

暂无评论...
验证码 换一张
取 消