2017-08-31 69 views
1

如果我有一個類:進口postsharp方面領域從類按名稱動態

class MyClass 
{ 
    IMyInterface _mi; 

    [MyAspectAttribute("_mi")] 
    bool _myValue; 

    // ... 
} 

有沒有一種方法來創建一個方面屬性MyAspectAttribute攔截獲取和設置(布爾myvalue的)的值,也進口在這種情況下,屬性[MyAspectAttribute(「_ mi」)]中指定的字段_mi是動態的,所以我可以在方面使用它? (我想在獲取或設置方面的字段之前調用接口)。

我知道如何編寫方面我只是不知道如何動態導入指定的字段(在本例中爲_mi)。所有的例子都需要你知道要導入的確切字段名稱(但我想把名字傳遞給我的方面)。

謝謝。

回答

0

您可以通過實施IAdviceProvider.ProvideAdvices方法併爲要導入的字段返回ImportLocationAdviceInstance來動態導入該字段。下面的示例方面演示了這種技術。

[PSerializable] 
public class MyAspectAttribute : LocationLevelAspect, IAdviceProvider, IInstanceScopedAspect 
{ 
    private string _importedFieldName; 

    public MyAspectAttribute(string importedFieldName) 
    { 
     _importedFieldName = importedFieldName; 
    } 

    public ILocationBinding ImportedField; 

    public IEnumerable<AdviceInstance> ProvideAdvices(object targetElement) 
    { 
     var target = (LocationInfo) targetElement; 
     var importedField = target.DeclaringType 
      .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 
      .First(f => f.Name == this._importedFieldName); 

     yield return new ImportLocationAdviceInstance(
      typeof(MyAspectAttribute).GetField("ImportedField"), 
      new LocationInfo(importedField)); 
    } 

    [OnLocationGetValueAdvice, SelfPointcut] 
    public void OnGetValue(LocationInterceptionArgs args) 
    { 
     IMyInterface mi = (IMyInterface)this.ImportedField.GetValue(args.Instance); 
     mi.SomeMethod(); 

     args.ProceedGetValue(); 
    } 

    [OnLocationSetValueAdvice(Master = "OnGetValue"), SelfPointcut] 
    public void OnSetValue(LocationInterceptionArgs args) 
    { 
     IMyInterface mi = (IMyInterface) this.ImportedField.GetValue(args.Instance); 
     mi.SomeMethod(); 

     args.ProceedSetValue(); 
    } 

    public object CreateInstance(AdviceArgs adviceArgs) 
    { 
     return this.MemberwiseClone(); 
    } 

    public void RuntimeInitializeInstance() 
    { 
    } 
}