Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

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

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 
{
    string Bar(int baz);
}

public class Foo : IFoo
{
    public string Bar(int baz) { return baz.ToString(); }
}

public class Proxy : IDynamicMetaObjectProvider
{
    private readonly object target;

    public Proxy(object target) { this.target = target; }

    // something clever goes here
}

Then I'm hoping there is some way to make it possible to write:

dynamic proxy = new Proxy(new Foo());
IFoo fooProxy = (IFoo)proxy; // because the target object implements it
string bar = fooProxy.Bar(123); // delegates through to the target implementation

But, as yet, I'm unsure what to replace // something clever goes here with.

So, my questions are:

  1. Is this actually possible to do with the dynamic runtime? It appears that dynamically implementing things like methods and properties is fairly easy, but I haven't found any documentation about dynamically implementing interfaces and conversions to them.

  2. Assuming this is possible, how difficult is it likely to be? (You can assume I'm a decent programmer with plenty of experience of things like reflection, but new to the dynamic framework.)

  3. Are there any resources which would help to point me in the right direction for implementing something like this? Or even samples where this kind of thing has already been done that I can use as a starting point?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The opensource framework Impromptu-Interface was designed to do this. It generates a cached lightweight proxy with a static interface and uses the dlr to forward the invocation to the original object.

using ImpromptuInterface;

public interface ISimpeleClassProps
{
    string Prop1 { get;  }

    long Prop2 { get; }

    Guid Prop3 { get; }
}

-

dynamic tOriginal= new ExpandoObject();
tOriginal.Prop1 = "Test";
tOriginal.Prop2 = 42L;
tOriginal.Prop3 = Guid.NewGuid();

ISimpeleClassProps tActsLike = Impromptu.ActLike(tOriginal);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...