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

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

问题描述

我有各种单独的方法,在继续自己的实现之前,它们都需要执行相同的功能.现在我可以在每种方法中实现这些功能,但是我想知道是否有一种方法可以利用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

Method-Level Aspects feature is available in the free edition: 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天全站免登陆