用于在运行时从接口生成具体类型的开源库?

发布于 2024-11-30 20:17:15 字数 453 浏览 1 评论 0原文

我正在开发一些需要接受合同(指定为接口)并动态创建实例的东西,而无需任何正式定义的满足此接口的具体类。

语法示例如下:

IExampleMessage message = MessageBuilder.Create<IExampleMessage>(x => {
   x.PropertyA = "Test";
   x.PropertyB = 5;
});

我见过其他 .NET 库和框架提供类似的行为(我想到了 NServiceBus),我想知道是否有一个 3rd 方库可以抽象运行时代码生成。我认为 Castle DynamicProxy 是一个值得一看的地方,但这似乎完全专注于代理和拦截,并且似乎没有公开代码生成方面。

我可以编写一个使用 Reflection.Emit 动态创建类的实现,但是我宁愿使用可靠的开源库(如果存在)。

有什么建议吗?

I'm working on something that needs to take in a contract (specified as an interface), and create a instance on the fly, without any formally defined concrete class that meets this interface.

An example of the syntax is like this:

IExampleMessage message = MessageBuilder.Create<IExampleMessage>(x => {
   x.PropertyA = "Test";
   x.PropertyB = 5;
});

I've seen other .NET libraries and frameworks offer behavior like this (NServiceBus comes to mind), and I'm wondering if there is a 3rd party library that abstracts the runtime code gen away. I thought Castle DynamicProxy would be a place to look, but this seems focused entirely on proxying and intercepting, and does not seem to expose the code generation aspect.

I could write up a implementation that uses Reflection.Emit to create the class on the fly, however I'd rather use a solid open source library if one exists.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心在旅行 2024-12-07 20:17:15

即兴界面正是您所需要的:- http://code.google.com/p/impromptu-接口/

我用它来创建.NET 中的多态类型

您还可以查看 粘土

Impromptu interface is what you need:- http://code.google.com/p/impromptu-interface/

I've used it to create polymorphic types in .NET.

You could also look at Clay.

风月客 2024-12-07 20:17:15

模拟库 - NMock 和 RhinoMocks 怎么样?

您也可以使用存根/期望将实现添加到具体类型。

Rhino 特别有一个很好的基于 lambda 的语法来满足你想要的那种东西。

这还不能完全满足您的需求吗?

像这样的东西吗?

IExampleMessage message = MockRepository.GenerateStub<IExampleMessage>();
message .Stub(x => x.PropertyA).Return("Text")    
message .Stub(x => x.PropertyB).Return(5)

What about the mocking libraries - NMock, and RhinoMocks?

You can add implementations to the concrete types using stubs/expectations as well.

Rhino in particular has a nice lambda based syntax for the kind of thing that you want.

Does this not full fill your needs?

Something like this?

IExampleMessage message = MockRepository.GenerateStub<IExampleMessage>();
message .Stub(x => x.PropertyA).Return("Text")    
message .Stub(x => x.PropertyB).Return(5)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文