问题
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