如何使用方法的参数属性 [英] How to use method parameter attributes

查看:117
本文介绍了如何使用方法的参数属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在苦苦寻找的属性,以验证方法的参数,即把这种形式如何编写自定义的例子:

 公共无效DoSomething的(客户端)
{
如果(client.HasAction(do_something))
{
// ...
$} b $ b,否则
{
抛出新RequiredActionException(客户端,do_something);
}
}



到这一点:

 公共无效DoSomething的([RequiredAction(ACTION =some_action)Client客户端)
{
// ...
}

据我所知道的,我需要这个属性添加到我的自定义属性,但我在关于如何访问装饰参数损耗客户端

  [AttributeUsageAttribute(AttributeTargets.Parameter)
公共类RequireActionAttribute:System.Attribute
{
公共类型动作{搞定;设置;}

公共RequireActionAttribute()
{
// ..你如何进入装修参数?
Client客户端=? (!client.HasAction(动作))

如果
{
抛出新RequiredActionException(客户端,行动);
}
}
}


解决方案

您正在正确应用 - 但一个属性基本上不知道它指的是成员。这肯定让生活更难了。



它不仅无法访问,它指的是成员,但该成员将是一个的ParameterInfo ,而不是客户端 - 有访问的的外部没有简单的方法。你的方法需要调用一些辅助代码,通过客户端的价值,以便适当地处理它...或者你需要挂接到它会调用代码你的方法入手,以发现的属性。



目前尚不清楚你究竟是如何希望利用这一点,但它可能是,你需要改变你的设计显著。


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);
        }
    }
}

解决方案

You're applying it correctly - but an attribute basically doesn't know the member it refers to. This definitely makes life harder.

Not only does it not have access to the member that it refers to, but that member would be a ParameterInfo, not a Client - there's no easy way of accessing the value of a parameter externally. Your method would need to call some helper code, passing the value of client in order to handle it appropriately... or you need to hook into the code which is going to call your method to start with, in order to notice the attribute.

It's not clear exactly how you were hoping to use this, but it may well be that you need to change your design significantly.

这篇关于如何使用方法的参数属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆