c# - 使用属性调用方法

标签 c# reflection architecture attributes aop

我有各种不同的方法,它们都需要在继续自己的实现之前执行相同的功能。现在我可以在每个方法中实现这些功能,但我想知道是否有一种方法可以利用 attributes 来做到这一点?举一个非常简单的例子,所有的网络调用都必须检查网络连接。

public void GetPage(string url)
{
   if(IsNetworkConnected())
      ...
   else
      ...           
}

这可行,但我必须为每个使用网络的方法调用 IsNetworkConnected 方法并单独处理它。相反,我想这样做

[NetworkCall]
public void GetPage(string url)
{
   ...
}

如果网络不可用,则调用错误方法并忽略 GetPage,否则调用 GetPage

这听起来很像面向切面编程,但我不想为了几个调用而实现整个框架。这更像是一种学习练习,而不是实现练习,所以我很好奇如何最好地实现这样的事情。

最佳答案

您可以使用 PostSharp , 它是.NET 的面向方面的框架,似乎quite easy to use :

static void Main(string[] args)
{
    Foo();
}

[IgnoreMethod(IsIgnored=true)]
public static void Foo()
{
    Console.WriteLine("Executing Foo()...");
}

[Serializable]
public class IgnoreMethodAttribute : PostSharp.Aspects.MethodInterceptionAspect
{
    public bool IsIgnored { get; set; }

    public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
    {
        if (IsIgnored)
        {
            return;
        }

        base.OnInvoke(args);
    }
}

方法级方面 功能在免费 版中可用:http://www.sharpcrafters.com/purchase/compare

运行时性能:

Because PostSharp is a compiler technology, most of the expensive work is done at build time, so that applications start quickly and execute fast. When generating code, PostSharp takes the assumption that calling a virtual method or getting a static field is an expensive operation. Contrary to rumor, PostSharp does not use System.Reflection at run time. http://www.sharpcrafters.com/postsharp/performance

关于c# - 使用属性调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211261/

相关文章:

c# - 测试条件如何基于查询结果的计数?

java - 从类名获取类成员

java - 如何实例化具有带参数的私有(private)构造函数的泛型类

java - 我应该为每种数据库查询创建新实体吗?

architecture - 如何管理微服务上的通用前端组件

c# - 从 PersistentDataPath 加载图像

c# - 3TB TXT 文件中的重复字符串

java - 如何在 Java 中获取方法的所有可能调用者 - 如调用层次结构

oop - 为对象或 Action /行为创建界面?

c# - 递归 for 循环代码的时间复杂度