該問題似乎與從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<>
(more on writing LinFu Dynamic Proxy interceptors here)