2016-09-18 27 views
0

我最近在PostSharp的支持論壇上發現了this question。看起來這個問題看起來不像這個問題,所以我現在要做。使用PostSharp引入通用/動態接口

原始問題詢問了通用接口。我對這樣做很感興趣,但我也有興趣簡單地在一個對象上動態地實現一個接口,同時指向一個代理實現。

以下是我正在嘗試完成的內容,但正如您所看到的,我在下面的標記行上發生錯誤,因爲IntroduceInterfaceAttribute不是IAspect

public class ApplyInterfaces : TypeLevelAspect, IAspectProvider 
{ 
    readonly Type[] interfaceTypes; 
    public ApplyInterfaces(params Type[] interfaceTypes) 
    { 
     this.interfaceTypes = interfaceTypes; 
    } 

    public IEnumerable<AspectInstance> ProvideAspects(object targetElement) 
    { 
     var type = (Type)targetElement; 
     var targetTypes = InterfaceTypeProvider.GetInterfacesFor(type); // pseudo-code. Get interfaces to implement "somewhere". 

     foreach (var interfaceType in interfaceTypes.Concat(targetTypes)) 
     { 
      yield return new AspectInstance(type, new IntroduceInterfaceAttribute(interfaceType)); // doesn't work. 
     } 
    } 
} 

PostSharp可以嗎?

+0

那麼究竟是什麼問題,你試圖解決。泛型或與實現接口有關的東西相當廣泛。請舉例說明你正在嘗試做什麼以及你嘗試使用什麼樣的 – Batavia

+0

這是你正在嘗試做什麼?http://www.postsharp.net/blog/post/PostSharp-Principals-Day-14-e28093 -Introducing-members-and-interfaces-Part-1(google中的第一個鏈接) – Batavia

+0

你是對的@Batavia,謝謝你的反饋。我可以在這個問題上投入更多精力。我已經更新了一些代碼和更多的上下文。我也在下面回答了我的問題,用我目前用來解決泛型接口問題的方法,使用(我相信的是)適配器模式。任何有關這些任何反饋意見將不勝感激! –

回答

0

下面是我目前正在解決這個問題,但我絕對可以反饋,如果有更好的方法。另外,我想驗證這確實也在使用the adapter pattern

[IntroduceInterface(typeof(IGenericInterface))] 
public class DynamicInterfaceAspect : InstanceLevelAspect, IGenericInterface 
{ 
    readonly Type parameterType; 

    public DynamicInterfaceAspect(Type parameterType) 
    { 
     this.parameterType = parameterType; 
    } 

    public override void RuntimeInitializeInstance() 
    { 
     var type = typeof(GenericInterfaceAdapter<>).MakeGenericType(parameterType); 
     Inner = (IGenericInterface)Activator.CreateInstance(type, Instance); 
    } 

    IGenericInterface Inner { get; set; } 
    public void HelloWorld(object parameter) => Inner.HelloWorld(parameter); 
} 

public interface IGenericInterface 
{ 
    void HelloWorld(object parameter); 
} 

public class GenericInterfaceAdapter<T> : IGenericInterface 
{ 
    readonly IGenericInterface<T> inner; 

    public GenericInterfaceAdapter(IGenericInterface<T> inner) 
    { 
     this.inner = inner; 
    } 

    public void HelloWorld(object parameter) => inner.HelloWorld((T)parameter); 
} 

public interface IGenericInterface<in T> 
{ 
    void HelloWorld(T parameter); 
} 
+0

由於您想提供代理實現,因此您可能也有興趣嘗試[CompositionAspect](http://doc.postsharp.net/t_postsharp_aspects_compositionaspect)。請注意,[IntroduceInterface]仍然是介紹接口的推薦方式。 – AlexD