Hi - i am using reflection to get information about a method in a derived class that has special attributes
and i need to create a Timer control and set the Timer.Tick event to the reflected method but i am not sure how
it is done in a right way.
Here is sample code:
MethodInfo mInfo = this .GetType().GetMethod( "MyMethod" , BindingFlags .IgnoreCase);
if (mInfo != null )
{
Attribute a = Attribute .GetCustomAttribute(mInfo, typeof ( MyControlBaseAttribute ));
if (a != null )
{
MyControlBaseAttribute attr = ( MyControlBaseAttribute )a;
int interval = attr.IntervalInMilliseconds;
Timer timer = new Timer ();
timer.Interval = (interval > 0) ? interval : 60000;
timer.ID = this .UniqueID + "_" + mInfo.Name + "Timer1" ;
timer.Tick += new EventHandler<EventArgs>(mInfo???); //<-- The problem }
}
}
解决办法
Like so?
MethodInfo method = this.GetType().GetMethod("MyMethod",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
EventHandler handler = (EventHandler) Delegate.CreateDelegate(
typeof(EventHandler), this, method);
//...
timer.Tick += handler;
Although it would be easier if you don't have to access MyMethod by name... for example, you could pass an EventHandler in as an argument to some method...
参考http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/3333df84-39ec-41a8-be0f-346ed33a06e5