SheepAspect 簡介以及代碼示列:
SheepAspect是一個AOP框架為.NET平台,深受AspectJ。它靜織目標組件作為一個編譯后的任務(編譯時把AOP代碼植入)。
多有特性時,可根據參數值設置先后進入順序


下面開始代碼實現之旅:
一、新建控制台程序:方案名稱:SheepAectTest

二、NuGet上搜索SheepAspect進行安裝

三、安裝完畢后的樣子


成員的切入點類型(SelectMethdos 以下圖等):

"saql":
| Criteria | Argument | Examples |
| Name | string |
|
| Namespace | string |
|
| ImplementsType | Type Pointcut |
|
| AssignableToType | Type Pointcut |
|
| HasMethod | Method Pointcut |
|
| HasProperty | Property Pointcut |
|
| HasField | Field Pointcut |
|
| ThisAspect | (none) |
|
| HasCustomAttributeType | Type Pointcut |
|
| InheritsType* | Type Pointcut |
|
| Interface* | (none) |
|
| Abstract* | (none) |
|
| ValueType* | (none) |
|
| Class* | (none) |
|
特性植入示列:
一、新建特性
public class LogAttribute:Attribute { public string Name { get; set; } public LogAttribute(string name) { Name = name; } }
二、新建一個測試類TestClass.cs
public class TestClass
{
[Log("獲取的第一個方法")]
public string Get()
{
return "test1";
}
public string Get2()
{
return "test2";
}
}
三、更改SampleAspect為:HasCustomAttributeType:'SheepAectTest.Attr.LogAttribute' > 命名空間+類名

四:編寫測試代碼:




輸出結果:

如果我們在AOP中更改結果呢?

輸出結果:

獲取特性的屬性:
[Aspect]
public class SampleAspect
{
[SelectMethods("HasCustomAttributeType:'SheepAectTest.Attr.LogAttribute'")]
public void PublicMethods() { }
[Around("PublicMethods", Priority = 100)]
public object LogAroundMethod(MethodJointPoint jp)
{
try
{
var log = (LogAttribute)jp.Method.GetCustomAttributes(typeof(LogAttribute), false)[0];
//這樣可以獲取屬性名稱:log.Name;
//jp.Args -> 包含傳遞參數
var result = jp.Execute();
if (jp.Method.ReturnType == typeof(void))
result = "{void}";
result = "AOP更改結果";
return result;
}
catch (Exception e)
{
throw;
}
}
}
多個特性注入順序以:Priority屬性值控制
優先級較低的值;

作者:瘋狂的果子
來源:http://incsharp.cnblogs.com/
聲明:原創博客請在轉載時保留原文鏈接或者在文章開頭加上本人博客地址,如發現錯誤,歡迎批評指正。如有特殊需求請與本人聯系!
