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

谁都会走 提交于 2019-12-05 14:27:32

问题


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 to make a dynamic proxy object, and want the method invocations on this class to be handled by the implementation of MyProxyClass.TryInvokeMember, which may or may not pass them on to a wrapped object.

Is this possible?

Thanks


回答1:


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<ExpandoObject>.NewObject(
         Prop1: "Test",
         Prop2: 42L,
         Prop3: Guid.NewGuid(),
         Meth1: Return<bool>.Arguments<int>(it => it > 5)
);

IMyInterface tActsLike = Impromptu.ActLike<IMyInterface>(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.




回答2:


With Clay, you can.

An example:

public interface IMyInterface
{
    string Prop1 { get; }

    long Prop2 { get; }

    Guid Prop3 { get; }

    Func<int, bool> Meth { get; }
}

//usage:

dynamic factory = new ClayFactory();
var iDynamic = factory.MyInterface
(
    Prop1: "Test",
    Prop2: 42L,
    Prop3: Guid.NewGuid(),
    Meth: new Func<int, bool>(i => i > 5)
);

IMyInterface iStatic = iDynamic;

This article shows few more ways to achieve this.




回答3:


Check out LinFu's proxies, mixins and duck typing.



来源:https://stackoverflow.com/questions/6712407/is-there-a-way-to-create-a-dynamicobject-that-supports-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!