我正在使用Linfu为接口生成代理对象。除了调用返回IEnumerable<object>的方法外,一切正常,我得到一个错误,如下所示:
无法将“< IEnumerableRpcCall >d__2”类型的对象强制转换为类型为
IEnumerableRpcCall是执行yield return object而不是return object的拦截器代码中方法的名称。
问题似乎在于,linfu返回的是指向方法的指针,而不是IEnumerable。有人找到解决办法了吗?
发布于 2012-06-04 11:40:01
这个问题似乎与从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<>的方法调用时,接口的代理对象不再抛出无效的强制转换异常。
(关于编写LinFu动态代理拦截器的更多信息)
https://stackoverflow.com/questions/10853969
复制相似问题