Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#泛型类中将两个可能的类型传递给T?_C#_Asp.net Core_Repository Pattern_Generic Programming - Fatal编程技术网

如何在C#泛型类中将两个可能的类型传递给T?

如何在C#泛型类中将两个可能的类型传递给T?,c#,asp.net-core,repository-pattern,generic-programming,C#,Asp.net Core,Repository Pattern,Generic Programming,我已经在Asp.Net核心应用程序中实现了Repository模式。我正在为基本存储库使用泛型类: public class GenericRepository<T> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T> where T : BaseEntity, new() { // Standard methods like: GetById, Update, De

我已经在
Asp.Net核心
应用程序中实现了
Repository模式
。我正在为基本存储库使用泛型类:

public class GenericRepository<T> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T>
    where T : BaseEntity, new()
{
    // Standard methods like: GetById, Update, Delete etc.
}
问题是我需要对所有其他存储库使用
GenericRepository
,但我的
ApplicationUser
实体扩展了
IdentityUser
而不是
BaseEntity


有没有办法让GenericRepository有两种可能的类型?
T
有时是
BaseEntity
还是有时是
IdentityUser

理论上,您可以这样做:

public class GenericRepository<T, TBase> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T>
    where T : TBase, new()
{
    // Standard methods like: GetById, Update, Delete etc.
}
公共类GenericRepository:IDisposable、IGenericRepository、IGenericRepositoryAsync
其中T:TBase,new()
{
//标准方法,如:GetById、Update、Delete等。
}
但我不清楚这将实现什么。通常,当您使用泛型条件时,这是因为类中的某些内容知道如何以某种特殊方式与条件中的类型(
BaseEntity
)交互

如果不是这样的话,那么这个标准首先就没有真正的意义,你应该删除它

如果是这种情况,您可能应该创建一个单独的存储库类型。例如,您可以有一个
GenericEntityRepository
,然后是一个单独的
IdentityUserRepository
或类似的东西。

当在诸如NHibernate或EntityFramework之类的ORM上使用时,这是一个反模式。ORM是更高层次的抽象。使用
BaseEntity
是另一个问题。ORMs允许您在添加任何类的同时使用该类,而添加该类型的操作正好相反。
public class GenericRepository<T, TBase> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T>
    where T : TBase, new()
{
    // Standard methods like: GetById, Update, Delete etc.
}