gpt4 book ai didi

c# - 具有通用类型约束的工厂模式

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:51 24 4
gpt4 key购买 nike

我正在实现一种工厂模式并找到了 this neat-looking pattern关于代码审查。

我已经通过以下一些变体实现了这个解决方案:

我有一个看起来像这样的工厂类:

public class SearchableServiceFactory<TSearchableLookupService, TOutputDto>
where TOutputDto : IBaseOutputDto
where TSearchableLookupService : ISearchableLookupService<TOutputDto>
{
static readonly Dictionary<string, Func<TSearchableLookupService>> _SearchableLookupServicesRegistry =
new Dictionary<string, Func<TSearchableLookupService>>();

private SearchableServiceFactory() { }

public static TSearchableLookupService Create(string key)
{
if (_SearchableLookupServicesRegistry.TryGetValue(
key, out Func<TSearchableLookupService> searchableServiceConstructor)
)
return searchableServiceConstructor();

throw new NotImplementedException();
}

public static void Register<TDerivedSearchableService>
(
string key,
Func<TSearchableLookupService> searchableServiceConstructor
)
where TDerivedSearchableService : TSearchableLookupService
{
var serviceType = typeof(TDerivedSearchableService);

if (serviceType.IsInterface || serviceType.IsAbstract)
throw new NotImplementedException();

_SearchableLookupServicesRegistry.Add(key, searchableServiceConstructor);
}

行得通。我从代码中调用它,因此:

...
SearchableServiceFactory<OrgLookupService, OrgOutputDto>.Register<OrgLookupService>
(
nameof(Organization), () => new OrgLookupService(_Context, _OrganizationRepository)
);
...

行得通。一个构造函数被添加到字典中,连同一个键。然后我去按键检索那个构造函数,得到一个实例并用它做一些事情,就像这样:

SearchableServiceFactory<ISearchableLookupService<IBaseOutputDto>, IBaseOutputDto>.Create(myKey).DoAThing();

失败是因为字典中不存在这样的值。因为它是静态的,类中注册和创建我需要的实例的方法也是静态的。

我正在使用 .NET Core 2.1,如果这很重要(这似乎是一个严格的 C# 问题)。

最佳答案

SearchableServiceFactory<OrgLookupService, OrgOutputDto>SearchableServiceFactory<ISearchableLookupService<IBaseOutputDto>, IBaseOutputDto> 的类型不同,因此,即使是静态属性也是不同的。

它们在编译器眼中是不同的类型。只因为 OrglookupServiceISearchableLookupService , 不是每个 ISearchableLookupServiceOrglookupService .

一个可能的解决方法是使用 SearchableServiceFactory<ISearchableLookupService<IBaseOutputDto>, IBaseOutputDto>注册您的对象,但这需要 ISearchableLookupService是协变的。

public interface ISearchableLookupService<out TOutputDto> 
where TOutputDto : IBaseOutputDto
{

}

然后像这样注册:

SearchableServiceFactory<ISearchableLookupService<IBaseOutputDto>, IBaseOutputDto>.Register<OrgLookupService>
(
nameof(Organization), () => new OrgLookupService()
);

关于c# - 具有通用类型约束的工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989020/

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