0

我试图找出是否可以设置自定义属性来确定方法调用是否可以处理。我想要的类似于[Authorize()]我在 MVC3 应用程序中使用的属性。

基本上,我有一个正在与之交互的 COM 对象(第 3 方 DMS 软件),我想确保用户在处理方法的内容之前没有关闭程序。我可以将调用包装在 a 中,try/catch或者我可以包装一个检查 的方法application.running,但我喜欢属性功能和简单的标记(如果需要)。

到目前为止,我发现的所有教程/文档都是如何使用属性标记方法/类(它们通常在教程中使用字符串),然后稍后在代码中访问这些字符串值。


如果可能的话,这不是我想做的事情。同样,在 MVC3/4 中,您可以这样做...

[Authorize()]
public class ControllerClass : Controller {
   public ActionResult Index(){ return View(); }
   ....etc....
}

在此示例中,索引始终必须由通过的人调用Authorize。我不确定是否需要实例化类或调用方法。

所以毕竟我的问题很简单。Authorize()可以为 C# WinForms 库实现类似的东西吗?

4

1 回答 1

2

是的,您可以通过PostSharp之类的AOP框架来实现它。样本:

[Serializable]
public class LogAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        if (!application.running)
            throw new Exception(String.Format("Method {0} is not allowed to call when application is not running.", args.Method.Name));
    }
}
于 2012-10-27T19:00:16.727 回答