自动创建包装器以实现接口 [英] Automatically creating a wrapper to implement an interface

查看:46
本文介绍了自动创建包装器以实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些实现某些接口但在结构上符合该接口的类.

I have some classes that don't implement a certain interface but structurally comply to that interface.

interface IFoo {
    void method();
}

class Bar {  // does not implement IFoo
   public void method() {...}
}

现在,我可以为那些只委托给包装后的类的类编写包装器

Now, I could write a wrapper around those classes that simply delegate to the wrapped class

class BarWrapper : IFoo {
   Bar bar = new Bar();
   public void method()
   {
      bar.method();
   }
}

但这是很多繁琐的工作.那些包装器类可以某种方式自动生成吗?像这样:

But that's lots of tedious work. Can those wrapper classes somehow be generated automatically? Something like:

IFoo foo = CreateWrapper< IFoo>(new Bar());

我确定您可以使用Reflection.Emit做到这一点,但我从未使用过它,乍一看它看起来并不容易.

I'm sure you could do this with Reflection.Emit but I've never used that and it doesn't look very easy at first glance.

有没有更简单的方法,或者也许有一个已经实现了此功能的库?

Is there an easier way or is there perhaps a library that already implements this?

推荐答案

您要完成的工作称为鸭类打字.有一些专用的库可以使您做到这一点,尽管我从未使用过它们.

What you're trying to accomplish, is known as duck typing. There are some dedicated libraries that will let you do that, although I haven't used any of them.

只需花费很少的精力(和一些反思),您就可以使用Castle Dynamic Proxy通过以下方法实现此目的:

With little effort (and some reflection) you can use Castle Dynamic Proxy to do that, using approach outlined here.

如果出于某种原因,基于拦截器的方法对您不可接受,则Dynamic Proxy尚不支持此功能(但),但是,如果您使用的是2.2 beta版,则很容易在一个强大的功能中提供该功能.通过提供您自己的代理类型生成器(看看mixins的实现方式)来实现键入方式(无需使用拦截器).

If for some reason the interceptor based approach would not be acceptable for you Dynamic Proxy does not support that out of the box (yet), but if you use version 2.2 beta, it would be fairly easy to provide that in a strongly typed manner (without using interceptors), by providing your own proxy type builder (take a look at how mixins are implemented).

这篇关于自动创建包装器以实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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