Is this a bug in dynamic?

前端 未结 2 654
暗喜
暗喜 2021-02-07 21:32

When implementing dynamic dispatch using dynamic on a generic class, and the generic type parameter is a private inner class on another class, the runtime binder th

2条回答
  •  Happy的楠姐
    2021-02-07 22:16

    It's a bug because the following static typing change should be equivalent

    using System;
    
    public abstract class Dispatcher
    {
        public T Call(int foo) { return CallDispatch(foo); }
        public T Call(string foo) { return CallDispatch(foo); }
    
        protected abstract T CallDispatch(int foo);
        protected abstract T CallDispatch(string foo);
    }
    

    And it works.

    This issue seems to be an issue with the compiler and the dlr calls it makes and the static information the compiler includes in the invocation. It can be worked around with the open source framework ImpromptuInterface that manually setups the dlr calls. With Impromptu by setting the context to this it's getting access permissions from the runtime type which will be TypeFinder.

    using System;
    using ImpromptuInterface.Dynamic;
    public abstract class Dispatcher
    {
        protected CacheableInvocation _cachedDynamicInvoke;
    
        protected Dispatcher()
        {
            _cachedDynamicInvoke= new CacheableInvocation(InvocationKind.InvokeMember, "CallDispatch", argCount: 1, context: this);
        }
    
        public T Call(object foo)
        {
            return (T) _cachedDynamicInvoke.Invoke(this, foo);
        }
    
        protected abstract T CallDispatch(int foo);
        protected abstract T CallDispatch(string foo);
    }
    

提交回复
热议问题