Z
Zach
I have a question re event handling. I have knocked up two examples,
code #one and code #two (below). Both do the same thing. I can
understand using event handling with respect to changed conditions of
controls, or subscribing to an event in a different class, but what use
would code #two be in other situations? Is it"l'art pour l'art"?
Code #one
using System;
namespace alternative
{
class Program
{
static void Main(string[] args)
{
int current = 0;
int previous = 0;
while(true)
{
System.DateTime dt = System.DateTime.Now;
current = dt.Second;
if(current %5 == 0 && current != previous)
Console.WriteLine("event raised {0}", current);
previous = current;
}
}
}
}
Code #two
using System;
namespace Event
{
public delegate void MyEventHandler(object o, MyEventArgs e);
public class MyEventArgs : EventArgs
{
public readonly int Second;
public MyEventArgs(int second)
{
this.Second = second;
}
}
public class Subscriber
{
public void show(object o, MyEventArgs e)
{
Console.WriteLine("Event raised by {0}", e.Second);
}
}
class Program
{
public static event MyEventHandler EventSecond;
public static void Main(string[] args)
{
int previous = 0;
System.DateTime current = System.DateTime.Now;
Subscriber Li = new Subscriber();
EventSecond += new MyEventHandler(Li.show);
while (true)
{
System.DateTime dt = System.DateTime.Now;
int sec = dt.Second;
MyEventArgs e = new MyEventArgs(sec);
if (sec%5 == 0 && sec != previous)
EventSecond(new Subscriber(), e);
previous = sec;
}
}
}
}
code #one and code #two (below). Both do the same thing. I can
understand using event handling with respect to changed conditions of
controls, or subscribing to an event in a different class, but what use
would code #two be in other situations? Is it"l'art pour l'art"?
Code #one
using System;
namespace alternative
{
class Program
{
static void Main(string[] args)
{
int current = 0;
int previous = 0;
while(true)
{
System.DateTime dt = System.DateTime.Now;
current = dt.Second;
if(current %5 == 0 && current != previous)
Console.WriteLine("event raised {0}", current);
previous = current;
}
}
}
}
Code #two
using System;
namespace Event
{
public delegate void MyEventHandler(object o, MyEventArgs e);
public class MyEventArgs : EventArgs
{
public readonly int Second;
public MyEventArgs(int second)
{
this.Second = second;
}
}
public class Subscriber
{
public void show(object o, MyEventArgs e)
{
Console.WriteLine("Event raised by {0}", e.Second);
}
}
class Program
{
public static event MyEventHandler EventSecond;
public static void Main(string[] args)
{
int previous = 0;
System.DateTime current = System.DateTime.Now;
Subscriber Li = new Subscriber();
EventSecond += new MyEventHandler(Li.show);
while (true)
{
System.DateTime dt = System.DateTime.Now;
int sec = dt.Second;
MyEventArgs e = new MyEventArgs(sec);
if (sec%5 == 0 && sec != previous)
EventSecond(new Subscriber(), e);
previous = sec;
}
}
}
}