gpt4 book ai didi

c# - 在运行时生成接口(interface)实现

转载 作者:行者123 更新时间:2023-12-03 10:23:30 25 4
gpt4 key购买 nike

我想问一下是否有一个库允许在运行时生成接口(interface)的实现,并具有如下所示的一些附加功能。

假设我有这样的界面:

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>()方法将在运行时创建这样的实现:
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) }
}
}

请问有什么想法吗?

最佳答案

正如jure所说,您可以为此使用DynamicProxy,但这将是应用于您的接口(interface)的JIT实现的方面。看看这个:http://jonas.follesoe.no/2009/12/23/automatic-inotifypropertychanged-using-dynamic-proxy/

PostSharp 在这个用例上也表现出色,但它是通过编译时编织与运行时 JIT'ing 完成的。 http://www.postsharp.net/aspects/examples/inotifypropertychanged

希望这可以帮助

关于c# - 在运行时生成接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com