Dynamically implementing an interface in .NET 4.0 (C#)

前端 未结 5 2091
情话喂你
情话喂你 2020-12-01 02:49

With the new dynamic capabilities in .NET 4.0, it seems like it should be possible to dynamically implement an interface, e.g. given:

public interface IFoo 
         


        
5条回答
  •  有刺的猬
    2020-12-01 03:29

    Explicit casting, as, and is fail because of type comparison would against your proxy base class, but implicit cast can trigger DynamicObject.TryConvert, such that you can then return inner object in-lieu of the dynamic object.
    - TryConvert MSDN Documentation

    While the code below works, this isn't interface delegation per se, only exposure of internal state. It sounds like you might be looking for something like an interception pattern such as Brian's DynamicWrapper.

    dynamic wrapper = new Proxy(new Foo());
    IFoo foo = wrapper;
    foo.Bar();
    
    class Proxy : DynamicObject
    {
        ...
    
        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            Type bindingType = binder.Type;
            if (bindingType.IsInstanceOfType(target))
            {
                result = target;
                return true;
            }
            result = null;
            return false;
    
        }
    
    }
    

提交回复
热议问题