用于声明抽象泛型类型变量的 C# 语法

标签 c# generics abstract-class

我有一个定义如下的类;

public abstract class Repository<TEntity, TDataContext> : DisposableBaseClass
   where TEntity : class
   where TDataContext : DataContext, new()
{...contains Linq to SQL related functionality

在具体的子类中,我这样定义类型;

public class ConcreteRepo : Repository<LSTableClass, LSDataContext>

在下一层,我有业务对象将 Repository 对象保存为私有(private)变量。

这很好;

private ConcreteRepo _repository;

但是,然后我将其重构为所有业务对象的父类 - 这个父类包含存储库/实现 Dispose 模式以处理存储库等。

我的问题是我无法获得变量声明的正确语法。

离我最近的是;

protected Repository<Object, DataContext> _repository;

但这给出了编译错误:

“错误 1 ​​'System.Data.Linq.DataContext' 必须是具有公共(public)无参数构造函数的非抽象类型,以便将其用作泛型类型或方法中的参数 'TDataContext' ... .Repository'...”

我尝试了其他各种方法,但遇到了其他问题。

在继承这个抽象类的业务层对象中,我创建并使用带有强制转换的 _repository 变量;

(Repository<LSTableClass, LSDataContext>)_repository = new ConcreteRepo();
  • 而且我认为这会很好,假设我可以在父级中正确地获得此声明。

如果我无法让它工作,我必须在每个业务对象中声明 _repository,并提供完整/具体的类型详细信息,并在每个业务对象中实现处置模式以进行清理。不是世界末日,但我希望不必如此。

最佳答案

如果我正确理解您的问题,您需要添加第三个通用参数,即存储库类型,它被限制为具有适当参数类型的 Repository 的后代。

进一步概述:

public abstract class Repository<TEntity,TDataContext>
    where TEntity : class
    where TDataContext : DataContext, new() {}

public abstract class BusinessObject<TEntity,TDataContext,TRepository>
    where TEntity : class
    where TDataContext : DataContext, new()
    where TRepository : Repository<TEntity,TDataContext>
{
    TRepository _repository;
}

public class ConcreteObject : BusinessObject<LSTableClass,LSDataContext,ConcreteRepo>
{ // ...

我知道它可能不像你想要的那么紧凑,但是要有效地减少它但仍然保留强类型,需要的是高阶泛型类型(在 Haskell 中称为类型类):一种指示类型参数的方法它们本身是通用的,并且可以采用类型参数。

关于用于声明抽象泛型类型变量的 C# 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/822326/

相关文章:

python - 在 Python 中,有什么方法可以从其父类调用子类的方法重写吗?

c# - 如何编写指定创建逻辑的接口(interface)或抽象类?

java - 使用 Gson 和抽象类

c# - 如何在 XAML (Xamarin Forms PCL) 中制作单选框

java - java中泛型子类的行为

具有多种类型的一个参数的C#泛型方法

.net - ADO.NET 疯狂和可空类型

c# - 有谁知道 EF Core 3.0 中的 IPluralizer、ICandidateNamingService 和 CandidateNamingService 发生了什么?

c# - 分析后台任务的内存使用情况

c# - DevExpress MVVM - 共享 ViewModel 和 EventToCommand