Can't use delegate in attribute


P

Paul E Collins

Hello.

I want an enum where each member corresponds to a method call - which
seems reasonable enough.

I tried something along these lines:

internal class MyAttribute : Attribute
{
public delegate void MyDelegate(int i);
MyDelegate m_d = null;
public MyAttribute(MyDelegate d) { m_d = d; }
}

// ... in another class ...
public enum Something
{
[MyAttribute(new MyAttribute.MyDelegate(SomeMethod))] Blah
}
private static void SomeMethod(int i) { }

However, I'm not allowed to create that MyDelegate within the enum,
because "an attribute argument must be a constant expression, typeof
expression or array creation expression".

What would you folks suggest as a workaround?

P.
 
Ad

Advertisements

P

Paul E Collins

Mohammad said:
Perhaps you could elaborate on what you are trying to
achieve here.

As I said, I want an enum where each member corresponds to a method
call.

P.
 
Ad

Advertisements

M

Mohammad

Thank you for pointing out that to me again, but that is not what I
meant. Obviously you are trying to solve a bigger problem here using
this technique, and, as you have noticed, it can't be done. My question
was about the bigger picture, in hope of finding another way to solve
your problem.

Anyway, if you must, an alternative might be to use reflection. If the
methods you want to call through the delegates are static, then you
could use an attribute that specifies the assembly name, fully
qualified class name, and method name as strings. And then use
reflection to invoke it at runtime.

But that's just jumping through too many hoops for my taste.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top