使用属性向方法添加参数 [英] Adding a parameter to a method using attributes

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

问题描述

诚然,这是一个远景.我正在处理一个审计部分,您可以在操作开始和结束时打开和关闭审计记录.我已经很好地装配了它,以便为了审计一个方法,你只需要在它上面添加一个 [Audit(AuditType.Something)] 属性,如果需要,再加上一些其他信息,比如消息.然后,使用 SNAP,我有一个拦截器来处理创建审计对象,然后打开和关闭它.

Admittedly, this one's a long shot. I'm working on an auditing piece where you open and close an audit record at the start and end of your action. I have it nicely rigged up so that in order to audit a method, you just have to add an [Audit(AuditType.Something)] attribute onto it, plus some other information if needed, like messages. Then, using SNAP, I have an interceptor that handles creating the Audit object, then opening and closing it.

一位同事提出了一个案例,我们需要在审计中使用非常量消息,这意味着它无法进入属性声明.我曾想过在类中粘贴一个 Audit 属性并让注入器在让方法继续之前设置它,但这似乎很草率,因为该属性可以被非审计对象访问,而且它会在很多地方.也有一些方法可以在没有属性的情况下创建审计,但能够将内容很好地包装在属性中会更好.

A case came up from a coworker where we would need to have a non-constant message in the audit, meaning it can't go into the attribute declaration. I've had thoughts about sticking an Audit property in the class and having the injector set it before letting the method continue, but that seems sloppy because the property would be accessable by non-audited objects, plus it would be duplicated in a lot of places. There are also ways to create the audit without the attribute, but it would be much nicer to be able to keep things nicely wrapped in the attribute.

理想的情况是,如果我能以某种方式设置它,以便具有 [Audit] 属性的方法可以访问一个变量,我可以将它们的审计对象从注入器中插入.这完全可能吗,还是只是一厢情愿?

The ideal case is if I could somehow set it up so that methods with the [Audit] attribute have access to a variable that I could stick their audit object in from the injector. Is this at all possible, or is it just wishful thinking?

推荐答案

如果您让 Audit 属性采用 Type 类型的参数,那么所提供的 Type 实现生成审计消息的接口?例如:

What if you have the Audit attribute take a parameter of type Type, where the provided Type implements an interface that produces your audit message? For instance:

public interface IAuditMessageProvider {
    public String MakeMeAnAuditMessage(/* some args perhaps */);
}

public class PiAuditMessageProvider : IAuditMessageProvider {
    public String MakeMeAnAuditMessage() { return "3.14"; }
}

[Audit(typeof(PiAuditMessageProvider))]
public void myMethod { ... }

然后您可以使用 Activator.CreateInstance 实例化提供的类型,将其转换为 IAuditMessageProvider,并调用相关方法.

Then you could instantiate the provided type using Activator.CreateInstance, cast it to IAuditMessageProvider, and call the relevant method.

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

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