[C#]RaiseEvent Extension Method (二)
public static void RaiseEvent(this object obj, EventHandler handler, Func<EventArgs> func)
{
if (handler == null)
return;
handler(obj, func());
}
public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler, TEventArgs e) where TEventArgs : EventArgs
{
RaiseEvent(obj, handler, () => e);
}
public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler,Func<TEventArgs> func) where TEventArgs : EventArgs
{
if (handler == null)
return;
handler(obj, func());
}
}</pre></div>
namespace ConsoleApplication14 { class Program { static void Main(string[] args) { Person Larry = new Person(); Larry.NameChanged += new EventHandler<NameEventArgs>(Larry_NameChanged); Larry.Name = “Larry”; } static void Larry_NameChanged(object sender, NameEventArgs e) { Console.WriteLine(string.Format(“NameChanged to {0}”, e.Name)); } } public static class ObjectExtension { public static void RaiseEvent(this object obj, EventHandler handler, EventArgs e) { RaiseEvent(obj, handler, () => e); }
public static void RaiseEvent(this object obj, EventHandler handler, Func<EventArgs> func)
{
if (handler == null)
return;
handler(obj, func());
}
public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler, TEventArgs e) where TEventArgs : EventArgs
{
RaiseEvent(obj, handler, () => e);
}
public static void RaiseEvent<TEventArgs>(this object obj, EventHandler<TEventArgs> handler,Func<TEventArgs> func) where TEventArgs : EventArgs
{
if (handler == null)
return;
handler(obj, func());
}
}
class NameEventArgs : EventArgs
{
public string Name { get; set; }
}
class Person
{
private string _name;
public string Name
{
get
{
if (_name == null)
return string.Empty;
return _name;
}
set
{
if (_name != value)
{
_name = value;
this.RaiseEvent(NameChanged, () => new NameEventArgs() { Name = value });
}
}
}
public event EventHandler<NameEventArgs> NameChanged;
}
}