key*_*rdP 13 c# architecture reflection aop attributes
我有各种各样的方法,在继续自己的实现之前都需要执行相同的功能.现在我可以在每种方法中实现这些功能,但我想知道是否有办法利用它attributes来做到这一点?作为一个非常简单的示例,所有网络呼叫都必须检查网络连接.
public void GetPage(string url)
{
if(IsNetworkConnected())
...
else
...
}
Run Code Online (Sandbox Code Playgroud)
这可行,但我必须为IsNetworkConnected使用网络的每个方法调用该方法并单独处理它.相反,我想这样做
[NetworkCall]
public void GetPage(string url)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果网络不可用,则会调用错误方法,但会GetPage被忽略,否则会GetPage被调用.
这听起来非常像Aspect Orientated Programming,但我不想为几个调用实现整个框架.这更像是一个学习练习而不是实现练习,所以我很好奇这样的事情是如何最好地实现的.
你可以使用PostSharp,它是面向方面的.NET框架,看起来很容易使用:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
免费版提供方法级方面功能:http://www.sharpcrafters.com/purchase/compare
运行时性能:
由于 PostSharp 是一种编译器技术,因此大部分昂贵的工作都是在构建时完成的,因此应用程序可以快速启动并快速执行。生成代码时,PostSharp 假设调用虚拟方法或获取静态字段是一项昂贵的操作。与传言相反,PostSharp 在运行时并不使用 System.Reflection。 http://www.sharpcrafters.com/postsharp/performance