简体   繁体   English

返回IEnumerable的Linfu动态代理和接口方法<object>

[英]Linfu dynamic proxy and Interface methods that return IEnumerable<object>

I am using Linfu to generate a proxy object for an interface. 我正在使用Linfu生成接口的代理对象。 Everything works fine except when calling a method that returns an IEnumerable<object> I get an error something like this: 一切正常,除了调用返回IEnumerable<object>的方法时,我收到如下错误:

Unable to cast object of type '< IEnumerableRpcCall >d__2' to type 'System.Collections.Generic.IEnumerable`1[System.String]'. 无法将类型为<< IEnumerableRpcCall> d__2'的对象转换为类型为'System.Collections.Generic.IEnumerable`1 [System.String]'。

FYI: IEnumerableRpcCall is the name of the method inside the interceptor code that does yield return object rather than return object . 仅供参考: IEnumerableRpcCall是拦截器代码内的方法名称,该方法确实yield return object而不是return object

It seems the problem is that linfu is returning a pointer to the method rather than an IEnumerable . 看来问题在于linfu正在返回指向该方法的指针,而不是IEnumerable Has anyone found a workaround for this? 有没有人找到解决方法?

The problem seems to be related to casting up from IEnumerable< object > to IEnumerable< string > (or whatever type). 问题似乎与从IEnumerable< object >IEnumerable< string > (或任何类型)有关。 I solved it by wrapping my enumerator logic inside a custom class that implements IEnumerable<T> : 我通过将枚举器逻辑包装在实现IEnumerable<T>的自定义类中来解决此问题:

  public class MyEnumerator<T> : IEnumerable<T>, IEnumerable
  {
        // custom logic here
  }

and then in my interceptor code I use reflection to instantiate the correct generic type as specified in the InvocationInfo object: 然后在我的拦截器代码中,使用反射实例化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...
       }
   }

And now the proxy object for my interface no longer throws an invalid cast exception when I make method calls that return IEnumerable<> 现在,当我进行返回IEnumerable<>方法调用时,接口的代理对象不再引发无效的强制转换异常

( more on writing LinFu Dynamic Proxy interceptors here ) 有关此处编写LinFu动态代理拦截器的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM