动态为Event增加处理函数的方法

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:

 

Code Snippet

 

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?

 

 

Code Snippet

            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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值