我一直在努力寻找如何编写自定义属性来验证方法参数的示例,即,转动这种形式:
public void DoSomething(Client client)
{
if (client.HasAction("do_something"))
{
// ...
}
else
{
throw new RequiredActionException(client, "do_something");
}
}
进入这个:
public void DoSomething([RequiredAction(Action="some_action")] Client client)
{
// ...
}
据我所知,我需要将此属性添加到我的自定义属性中,但我不知道如何访问修饰参数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);
}
}
}