1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public static IObservable<T> Event2Observable<TSource, T>(
this TSource source, string eventName)
where TSource : class
{
EventInfo info = source.GetType()
.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance);
if(info == null)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture,
"Could not find event '{0}' on object of type '{1}'.",
new object[] { eventName, source.GetType().FullName }));
}
return Observable.Create<T>(o =>
{
Action<T> handler = o.OnNext;
info.AddEventHandler(source, handler);
return () => info.RemoveEventHandler(source, handler);
});
}
|