开发者

Custom Events for Integers

I know how silly this may sound, but is there a way to attach an event to an integer?

For example, if you're in a w开发者_开发知识库hile loop and you do: i++; is it at all possible to do something like this?:

int i;

Form1_Load(object sender, EventArgs e)
{
   i.MaximumNumberReached += new IntegerMaximumNumberReachedEventArgs();
}

while(x != y)
{
   i++
}

private void MaximumNumberReached(object sender, EventAgrs e)
{
   if(e.Value == 7)
   {
      this.Dispose(true);
   }
}

Or should I just stop using my imagination so much?

Thank you


Firstly, no, you can't do that. You could if, say, you had your own class representing numbers and overloaded relevant operators such that they initiated certain events, but you can't invent events and attach them to existing classes (aside, say, from using an AOP framework and hooking into certain methods).

Secondly, no, don't stop using your imagination. You may be interested in the following article: Arithmetic Overflow Checking.


You can't add events to a type outside of your control, and events on structs is usually a very bad idea; but: the best approach here would be to use a property:

private int someMeaningfulName;
public int SomeMeaningfulName {
    get { return someMeaningfulName; }
    set {
        // pre-validation checks and "changing" notification
        someMeaningfulName = value;
        // side effect code and "changed" notification
    }
}


Extension methods? Not events but you can do something similar. http://msdn.microsoft.com/en-us/library/bb383977.aspx

class Program
{
    static void Main(string[] args)
    {
        int a = 10;
        a.MaximumNumberReached();
    }
}

public static class Extns
{
    public static void MaximumNumberReached(this int number)
    {
        if (number == 7)
        {
            //Do something
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜