Can one use [CustomAttribute] with anonymous in-line delegates?

只愿长相守 提交于 2019-12-11 19:58:54

问题


With the [attribute] notation I can attach custom attributes to class instance methods. But if I write code like

menu.handlers[MOUSECLICK] += (clickEvent)delegate(event e) { ... };

the [attribute] notation seems not to be available. Am I limited to attributes for methods declared out of line, or is there a way to somehow do them for in-line anonymous methods declared using delegate() { ... }?

(I happen to like the inline style: you have easy access to in-scope variables and I think it makes for a nicer and more compact kind of code where you can see what the event handler will do at the same place where you register it...)


回答1:


The anonymous method is defined in-line and not as a member method of any class. Additionally, there is no way to apply custom attributes to an anonymous method, nor can the anonymous method define generic types or add generic constraints.

Quoting from the MSDN Article - Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes

In Short NO!, You cannot add custom attributes for Anonymous methods



来源:https://stackoverflow.com/questions/9926378/can-one-use-customattribute-with-anonymous-in-line-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!