![](/img/trans.png)
[英]Can I use Linfu dynamic proxy to proxy an interface with generic parameters?
[英]Linfu dynamic proxy and Interface methods that return IEnumerable<object>
我正在使用Linfu生成接口的代理對象。 一切正常,除了調用返回IEnumerable<object>
的方法時,我收到如下錯誤:
無法將類型為<< IEnumerableRpcCall> d__2'的對象轉換為類型為'System.Collections.Generic.IEnumerable`1 [System.String]'。
僅供參考: IEnumerableRpcCall
是攔截器代碼內的方法名稱,該方法確實yield return object
而不是return object
。
看來問題在於linfu正在返回指向該方法的指針,而不是IEnumerable
。 有沒有人找到解決方法?
問題似乎與從IEnumerable< object >
為IEnumerable< string >
(或任何類型)有關。 我通過將枚舉器邏輯包裝在實現IEnumerable<T>
的自定義類中來解決此問題:
public class MyEnumerator<T> : IEnumerable<T>, IEnumerable
{
// custom logic here
}
然后在我的攔截器代碼中,使用反射實例化InvocationInfo對象中指定的正確的泛型類型:
private class MyLinfuInterceptor : IInterceptor
{
public object Intercept(InvocationInfo info)
{
MethodInfo methodBeingRequested = info.TargetMethod;
// enumerable return type
if (methodBeingRequested.ReturnType.IsGenericType
&& methodBeingRequested.ReturnType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
&& methodBeingRequested.ReturnType.GetGenericArguments().Length == 1)
{
Type constructedEnumerator = typeof(MyEnumerator<>).MakeGenericType(methodBeingRequested.ReturnType.GetGenericArguments());
var result = Activator.CreateInstance(constructedEnumerator);
return result;
}
// code to handle other return types here...
}
}
現在,當我進行返回IEnumerable<>
方法調用時,接口的代理對象不再引發無效的強制轉換異常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.