Well i need some help here i don’t know how to solve this problem.
the function of the attribute is to determine if the function can be run…
So what i need is the following:
- The consumer of the attribute should
be able to determine if it can be
executed. - The owner of the attribute should be
able to tell the consumer that now it
can/can’t be executed (like a
event). - It must have a simple syntax.
This is what i have so far but it only implements point 1, 3.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ExecuteMethodAttribute : Attribute
{
private Func<object, bool> canExecute;
public Func<object, bool> CanExecute
{
get
{
return canExecute;
}
}
public ExecuteMethodAttribute()
{
}
public ExecuteMethodAttribute(Func<object, bool> canExecute)
{
this.canExecute = canExecute;
}
}
Attributes are not intended for this type of purpose. You decorate a Type with an attribute, not a specific instance.
If you need a way to specify, to a consumer, that a specific method is ready to execute, or cannot execute, I would rethink your design. Instead of using an attribute, perhaps making a custom class would work much more appropriately.
Given your design, I would recommend taking a look at the ICommand interface. This basically does exactly what you are trying to do. It encapsulates a delegate into a class, with a “CanExecute” method, and an event for notifying “consumers” that the execution availability has changed. This would be a more appropriate option.