在 .NET 4.0 (C#) 中动态实现接口 [英] Dynamically implementing an interface in .NET 4.0 (C#)

查看:63
本文介绍了在 .NET 4.0 (C#) 中动态实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 .NET 4.0 中的新动态功能,似乎应该可以动态实现接口,例如给定:

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.

所以,我的问题是:

  1. 这真的可能与动态运行时有关吗?似乎动态实现方法和属性之类的东西相当容易,但我还没有找到任何关于动态实现接口和对它们的转换的文档.

  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.

假设这是可能的,它可能有多困难?(你可以假设我是一个体面的程序员,在反射等方面有丰富的经验,但对动态框架不熟悉.)

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.)

是否有任何资源可以帮助我指明实施此类事情的正确方向?或者甚至是已经完成此类事情的样本,我可以将其用作起点?

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?

推荐答案

据我所知,没有人工干预是不可能编写或生成将接口成员转发到包装实例的代码的.如果您希望看到 Microsoft 对此类事情提供的支持,您可能需要考虑在 https://connect.microsoft.com/VisualStudio/feedback/details/526307/add-automatic-generation-of-interface-implementation-via-implementing-member.

As far as I know, it's not possible without manual intervention to write or generate code that forwards the interface members to the wrapped instance. If you would like to see Microsoft-provided support for this sort of thing, you might want to consider voting at https://connect.microsoft.com/VisualStudio/feedback/details/526307/add-automatic-generation-of-interface-implementation-via-implementing-member .

这篇关于在 .NET 4.0 (C#) 中动态实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆