gpt4 book ai didi

c# - 如何为类型设置约束,使其必须是另一种泛型类型

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:59 25 4
gpt4 key购买 nike

这可能是以前问过的,但我无法解决。也许如果我能把标题弄对,我就可以用谷歌搜索它。

我有这个通用的存储库接口(interface):

public interface IRepository<TEntity>
{
TEntity Resolve<TEntity>(); // dummy function, just to get the idea
}

我还有一个通用工作单元,它能够解析通用存储库:

public interface IUnitOfWork
{
IRepository<TEntity> GetGenericRepository<TEntity>() where TEntity : class;
}

到目前为止一切顺利。

但是随着现实生活的继续,我想创建一个具有一些特定功能的自定义存储库。所以我在想:继承;像这样:

public class SpecialRepository : IRepository<SomeEntityType>
{
public void SomeSpecialFunction() { };
}

显然,这种类型不能用 GetGenericRepository 解析方法所以我想:让我们添加一个额外的方法到 IUnitOfWork接口(interface):

public interface IUnitOfWork
{
//same old get generic repository
IRepository<TEntity> GetGenericRepository<TEntity>() where TEntity : class;

//the newly added.
T GetInheretedRepository<T>() where T : class;
}

我希望能够使用特殊存储库调用工作单元,如下所示:

public test()
{
IUnitOfWork uow = new UnitOfWork();

//I want to make this call with a constraint on TemplateRepo
//to enforce it's type: IRepository<T> (which TemplateRepo is)
var y = uow.GetInheretedRepository<TemplateRepo>();
}

问题是:我如何限制类型 TT GetInheretedRepository<T>() where T : class;类型:IRepository<TEntity>

我试过这个:

public interface IUnitOfWork
{
//the newly added.
//error: Only class or interface could be specified as constraint
T GetInheretedRepository<T>() where T : class, IRepository; }

public interface IUnitOfWork
{
//the newly added.
//error: type argument missing
T GetInheretedRepository<T>() where T : class, IRepository<>;
}

那行不通。

我可以放弃约束作为快速修复或者创建一个继承的工作单元,但是随后;问题仍然存在。

最佳答案

这样做的方法是添加第二个泛型类型参数,如下所示:

TRepository GetInheretedRepository<TRepository, TEntity>() 
where TRepository : IRepository<TEntity>
where TEntity : class;

此处您提供存储库类型和实体类型。这样 C# 编译器可以检查类型是否匹配。调用方法如下:

var rep = uow.GetInheretedRepository<SpecialRepository, SomeEntityType>();

rep.SomeSpecialFunction();

这显然很糟糕,因为您必须指定这两种类型。但更重要的是,这很糟糕,因为您必须指定具体类型,从而使您的代码依赖于具体类型;违反了 Dependency Inversion Principle

我真的很想建议远离依赖于具体类型的设计,或者更好的是,远离在特定存储库类上有许多方法的设计,因为这违反了 SRPOCPISP,这可能会导致以后的维护问题。

因此,请查看 this article 中描述的应用程序设计。

关于c# - 如何为类型设置约束,使其必须是另一种泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946789/

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