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