在运行时生成接口实现 [英] Generating interface implementation at runtime
问题描述
我想问一下是否有一个库,该库可以在运行时生成接口的实现,并具有以下所示的一些其他功能。
I would like to ask is there a library which allows to generate implementation of interface at runtime with some additional features illustrated below.
假设我有这样的接口:
interface ICustomer
{
string Name {get;set;}
string IAddress { get;set; }
}
interface IAddress
{
string Street {get;set;}
}
我想做这样的事情:
ICustomer customer = someLibrary.Create<ICustomer>(bool createSubObjects)
其中 Create< ; T>()
方法将在运行时创建这样的实现:
where Create<T>()
method would create an implementation like this at runtime:
class RuntimeCustomer : NotifyPropertyChanged,ICustomer
//NotifyPropertyChanged would be hand written class
{
string name;
IAddress address = new RuntimeAddress();
//if createSubObjects == false then `IAddress address = null`
public string Name
{
get { return name; }
set { SetProperty(ref name, value); }
}
public IAddress Address
{
get { return address; }
set { SetProperty(ref address, value) }
}
}
class RuntimeAddress : NotifyPropertyChanged, IAddress
{
string street;
public string Street
{
get { return street; }
set { SetProperty(ref,street, value) }
}
}
请问有什么想法吗?
推荐答案
如法律上所说的,您可以为此使用DynamicProxy,但这将是适用的方面到界面的JIT实现。请查看以下内容: http://jonas.follesoe。 no / 2009/12/23 / automatic-inotifypropertychanged-using-dynamic-proxy /
as jure said you can use DynamicProxy for this, but it would be aspects applied to a JIT'ed implementation of your interfaces. Check this out: http://jonas.follesoe.no/2009/12/23/automatic-inotifypropertychanged-using-dynamic-proxy/
PostSharp在此用例上也很出色,但这是由编译时编织与运行时JIT'ing。 http://www.postsharp.net/aspects/examples/inotifypropertychanged
PostSharp excels at this use case as well, but it's done by compile-time weaving vs. runtime JIT'ing. http://www.postsharp.net/aspects/examples/inotifypropertychanged
希望这会有所帮助
这篇关于在运行时生成接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!