简体   繁体   中英

How can I pass two possible type to T in C# generic class?

I have implemented Repository Pattern in Asp.Net Core application. I'm using generic class for base repository:

public class GenericRepository<T> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T>
    where T : BaseEntity, new()
{
    // Standard methods like: GetById, Update, Delete etc.
}

I have Specific repositories following my Domain : FeedRepository , UserRepository . And Entities : Post , ApplicationUser .

My FeedRepository looks like this:

public class FeedRepository : GenericRepository<Post>, IFeedRepository
{
    // Specific methods for Feed
}

The problem is that I need to use GenericRepository for all my other repositories, but my ApplicationUser entity extends IdentityUser not BaseEntity .

Is there any way to have 2 possible types for GenericRepository? Can T be sometimes BaseEntity and sometimes IdentityUser ?

Well, in theory, you could do this:

public class GenericRepository<T, TBase> : IDisposable, IGenericRepository<T>, IGenericRepositoryAsync<T>
    where T : TBase, new()
{
    // Standard methods like: GetById, Update, Delete etc.
}

But it's unclear to me what that would accomplish. Usually when you use generic criteria it's because something in your class knows how to interact with the type in the criteria ( BaseEntity ) in some special way.

If that's not the case, then there's no real purpose for that criteria in the first place, and you should just remove it.

If that is the case, you should probably create a separate repository type. For example, you can have a GenericEntityRepository and then a separate IdentityUserRepository or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM