使用属性调用方法 [英] Using Attributes to Call Methods

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

问题描述

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

I have various individual methods which all need to perform the same functions before continuing on with their own implementation. Now I could implement these functions in each method, but I was wondering if there's a way to exploit attributes to do this? As a very simple example, all network calls have to check for a network connection.

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

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

This would work, but I'd have to call the IsNetworkConnected method for each method that uses the network and handle it individually. Instead, I'd like to do this

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

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

If the network is unavailable, an error method is called instead and GetPage is ignored, otherwise GetPage is invoked.

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

This sounds very much like Aspect Orientated Programming, but I don't want to implement an entire framework for a few calls. This is more of a learning exercise than an implementation one, so I was curious as to how something like this would be best implemented.

推荐答案

您可以使用 PostSharp,它是.NET 的面向方面的框架,看起来很容易使用:

You can use PostSharp, it is aspect-oriented framework for .NET, it seems 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

运行时性能:

因为 PostSharp 是一种编译器技术,大部分昂贵的工作都是在构建时完成的,因此应用程序启动速度快,执行速度快.在生成代码时,PostSharp 假设调用虚拟方法或获取静态字段是一项开销很大的操作.与谣言相反,PostSharp 在运行时不使用 System.Reflection.http://www.sharpcrafters.com/postsharp/performance

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

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

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