Is there a way to create a DynamicObject that supports an Interface?

后端 未结 3 2214
逝去的感伤
逝去的感伤 2021-02-19 15:27

Can I define a class which derives from DynamicObject and supports an interface (ICanDoManyThings) without having to implement each method in the interface?

I\'m trying

3条回答
  •  死守一世寂寞
    2021-02-19 15:50

    ImpromptuInterface does exactly this and it works with ANY IDynamicMetaObjectProvider including DynamicObject subclasses and ExpandoObject.

    using ImpromptuInterface;
    using ImpromptuInterface.Dynamic;
    
    public interface IMyInterface{
    
       string Prop1 { get;  }
    
        long Prop2 { get; }
    
        Guid Prop3 { get; }
    
        bool Meth1(int x);
    }
    

    ...

    //Dynamic Expando object
    dynamic tNew = Build.NewObject(
             Prop1: "Test",
             Prop2: 42L,
             Prop3: Guid.NewGuid(),
             Meth1: Return.Arguments(it => it > 5)
    );
    
    IMyInterface tActsLike = Impromptu.ActLike(tNew);
    

    Linfu won't actually use DLR based objects and rather uses it's own naive late binding which gives it a SERIOUS performance cost. Clay does use the dlr but you have to stick with Clay objects which are designed for you to inject all behavior into a ClayObject which isn't always straightforward.

提交回复
热议问题