【问题标题】:How can I pass two possible type to T in C# generic class?如何在 C# 泛型类中将两种可能的类型传递给 T?
【发布时间】:2019-09-30 13:24:07
【问题描述】:

我在Asp.Net Core 应用程序中实现了Repository Pattern。我正在使用通用类作为基础存储库:

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

我的Domain 后面有特定的存储库:FeedRepositoryUserRepository。还有EntitiesPostApplicationUser

我的FeedRepository 看起来像这样:

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

问题是我需要为所有其他存储库使用GenericRepository,但我的ApplicationUser 实体扩展IdentityUser 而不是BaseEntity

有没有办法让 GenericRepository 有 2 种可能的类型? T 可以有时是BaseEntity 有时是IdentityUser 吗?

【问题讨论】:

  • 在 NHibernate 或 EntityFramework 等 ORM 之上使用时,这是一个模式。 ORM 是更高级别的抽象。使用BaseEntity 是另一个问题。 ORM 允许您使用任何类,而添加该类型则相反。

标签: c# asp.net-core repository-pattern generic-programming


【解决方案1】:

嗯,理论上,你可以这样做:

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

但我不清楚这会带来什么。通常,当您使用通用标准时,这是因为您的类中的某些内容知道如何以某种特殊方式与标准中的类型 (BaseEntity) 进行交互。

如果不是这样,那么该标准一开始就没有真正的目的,您应该删除它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多