c# - 可以在泛型类型约束上指定它必须实现泛型类型吗?

标签 c# .net generics type-constraints

这是我想做的:

public interface IRepository<TSet<TElement>> where TSet<TElement> : IEnumerable<TElement>
{
    TSet<TEntity> GetSet<TEntity>();
}

在 .NET 中可以进行这样的构造吗?

编辑:问题不够清楚。这是我想做的,展开:

public class DbRepository : IRepository<DbSet<TElement>> {
    DbSet<TEntity> GetSet<TEntity>();
}

public class ObjectRepository : IRepository<ObjectSet<TElement>> {
    ObjectSet<TEntity> GetSet<TEntity>();
}

意思是,我希望约束类型: - 接受一个通用参数 - 实现给定的单个通用参数接口(interface)。

这可能吗?事实上,我只会对第一件事感到高兴。

public interface IRepository<TGeneric<TElement>> {
    TGeneric<TArgument> GetThing<TArgument>();
}

最佳答案

您需要使用两种泛型类型来实现这一点,例如:

public interface IRepository<TCollection, TItem> where TCollection : IEnumerable<TItem>
{
    TCollection GetSet<TItem>();  
}

(我假设 TEntity 应该是原始的 TElement...)

话虽这么说,但最好是这样写:

public interface IRepository<T>
{
    IEnumerable<T> GetSet<T>();  
}

这将是实现上述目标的更常用方法。

关于c# - 可以在泛型类型约束上指定它必须实现泛型类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5327904/

相关文章:

c# - 基于运行时类型而非编译时类型的调用方法

c++ - 无法将函数定义与 cpp 中的现有声明相匹配

c# - 在 C# 中执行此通用抽象类的最佳方法?

c# - 手机手电筒用xamarin打开但是没有打开,为什么?

.net - 使用样式将控件包裹在边框中而不覆盖默认外观

java - 泛型(列表)打字问题

c# - C# 中的 if (string) 与 if (bool)

c# - 缓慢迁移公共(public)网站

c# - 在 asp.net 视频上创建控件时出错

c# - System.IO.Directory.Move(tempPath, newFolder) 抛出异常访问被拒绝