473,383 Members | 1,829 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Firing Events using reflection

I looked high and low for code to do this and finally found some VB
code that did it right.

This is a C# flavor of it.

public event EventHandler<EventArgsMyEventToBeFired;

public void FireEvent(Guid instanceId, string handler)
{
EventArgs e = new EventArgs(instanceId);

MulticastDelegate eventDelagate =
(MulticastDelegate)GetType().GetField(handler,
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic).GetValue (this);

Delegate[] delegates = eventDelagate.GetInvocationList();

foreach (Delegate dlg in delegates)
{
dlg.Method.Invoke(dlg.Target, new object[] { this, e
});
}
}

FireEvent("Some Data string arg that so happens to be a GUID",
"MyEventToBeFired");

Nov 22 '06 #1
2 2635
Firing events via reflection is always going to be dodgy as heck. In
particular, you have know way of knowing what the backer is. Is *might* be a
compiler-built field, but it might be a separate field I provide (perhaps
through a facade to an encapsulated class), or it might be via an
EventHandlerList, or about 17 other things. So you can't rely on reflection
to work unless you know what class you are dealing with and how the event is
implemented.

Even within a class you own, this would mandate some kind of switch or
dictionary; as a thought, it would be quite easy to create a variant of
EventHandlerList that works on Dictionary<string, EventHandler>, and lets
you do all of this just using the handler (string) directly as the key...
i.e. something like below...

But as a general principal, events should be fired from *within* a class,
not from outside.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;

public class MyData
{
public event EventHandler SomeEvent1 {
add { events.Add("SomeEvent1", value); }
remove { events.Remove("SomeEvent1", value); }
}
private readonly DelegateDictionary events = new DelegateDictionary();
public event EventHandler SomeEvent2
{
add { events.Add("SomeEvent2", value); }
remove { events.Remove("SomeEvent2", value); }
}
public event EventHandler SomeEvent3
{
add { events.Add("SomeEvent3", value); }
remove{ events.Remove("SomeEvent3", value); }
}
public void FireEvent(string name)
{
events.InvokeHandler(name, this);
}

}
class Program
{
static void Main()
{
MyData data = new MyData();
data.SomeEvent1 += new EventHandler(data_SomeEvent1);
data.SomeEvent2 += new EventHandler(data_SomeEvent2);
data.SomeEvent2 += new EventHandler(data_SomeEvent2);
data.FireEvent("SomeEvent2");
data.FireEvent("SomeEvent1");
data.FireEvent("SomeEvent3");// not subscribed
data.FireEvent("SomeDuffEvent");
}

static void data_SomeEvent1(object sender, EventArgs e)
{
Debug.WriteLine("data_SomeEvent1");
}
static void data_SomeEvent2(object sender, EventArgs e)
{
Debug.WriteLine("data_SomeEvent2");
}
}

public class DelegateDictionary
{
private readonly Dictionary<string, Delegatedata = new
Dictionary<string, Delegate>();

public void InvokeHandler(string key, object sender)
{
EventHandler handler = GetHandler(key);
if (handler != null) handler(sender, EventArgs.Empty);
}
public void Invoke(string key, params object[] parameters)
{
Delegate handler = this[key];
if (handler != null) handler.DynamicInvoke(parameters);
}
public EventHandler GetHandler(string key)
{
return (EventHandler) this[key];
}
public T Get<T>(string key)
{
return (T)(object)this[key];
}
public Delegate Get(string key)
{
return this[key];
}
public void Add(string key, Delegate handler)
{
if (handler == null) return;
Delegate current;
if (data.TryGetValue(key, out current))
{
data[key] = Delegate.Combine(current,handler);
}
else
{
data.Add(key, handler);
}
}
public void Remove(string key, Delegate handler)
{
if (handler == null) return;
Delegate current;
if (data.TryGetValue(key, out current))
{
data[key] = Delegate.Remove(current, handler);
}
}
public Delegate this[string key]
{
get
{
Delegate handler;
data.TryGetValue(key, out handler);
return handler;
}
}
}
Nov 22 '06 #2
Minor edit to clean up the dictionary when un-subscribing; you could even go
overboard and create / release the "data" field as the count of delegates
changes between 0 and >0

Still not sure it is a great idea *for calling from externally*, but an
interesting diversion ;-p

Marc

public void Remove(string key, Delegate handler) {
if (handler == null) return;
Delegate current;
if (data.TryGetValue(key, out current))
{
Delegate result = Delegate.Remove(current, handler);
if (result == null) {
data.Remove(key);
} else {
data[key] = result;
}
}
}
Nov 22 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Tim Haughton | last post by:
Can anyone tell me how to dynamically fire an event? I have an object that reflects on which events it has and based on some logic, elects which one to fire. Or at least that's the plan. So...
3
by: Mike | last post by:
Hi, I am adding controls dynamically in a WebForm, but none of these controls' events fire. Here is the class code I am using. I have tried so many things, but nothing works :-( namespace...
7
by: Denise | last post by:
I just realized the DataTable_RowChanging events were firing when I called Fill method of the DataAdapter! It fires TWICE for each row loaded. I thought these were only supposed to be called when...
28
by: Tim_Mac | last post by:
hi, i'm new to .net 2.0, and am just starting to get to grips with the gridview. my page has autoEventWireUp set to true, which i gather is supposed to figure out which handlers to invoke when...
30
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment...
19
by: furiousmojo | last post by:
This is a strange problem. I have a project where the contents of global.asax application_error are not firing. It is an asp.net 2.0 application using web application projects. I have another...
5
by: Joe | last post by:
Hi I am adding a class to a ComboBox - and all is fine except that I fill the combobox on the Form_Load Method and it causes the method private void comboBox2_SelectedIndexChanged(object...
0
by: RobKinney1 | last post by:
Hello, One of our C# apps (2.0) depends on a few events. One of them being DocumentComplete. Well, everything works fine with users that have IE 6 installed on their computers. But we noticed...
4
by: Joergen Bech | last post by:
I sometimes use delegates for broadcasting "StateChanged" events, i.e. if I have multiple forms and/or controls that need updating at the same time as the result of a change in a global/common...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.