这是我想做的:
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/