I've been struggling to find examples of how to write a custom attribute to validate method parameters, i.e., turn this form:
public void DoSomething(Client client)
{
if (client.HasAction("do_something"))
{
// ...
}
else
{
throw new RequiredActionException(client, "do_something");
}
}
into this:
public void DoSomething([RequiredAction(Action="some_action")] Client client)
{
// ...
}
As far as I can tell, I need to add this attribute to my custom attribute, but I'm at a loss on how to access the decorated parameter Client
:
[AttributeUsageAttribute(AttributeTargets.Parameter)]
public class RequireActionAttribute : System.Attribute
{
public Type Action {get; set;}
public RequireActionAttribute()
{
// .. How do you access the decorated parameter?
Client client = ???
if (!client.HasAction(Action))
{
throw new RequiredActionException(client, Action);
}
}
}
IDoSomething
. – Sociolinguistics