C#(泛型的泛型)是什么?

4
有没有办法在C#中表达这个想法?(基本上是一个泛型类型的泛型类型)?
public static class ExtensionSpike
{
    public static IEnumerable<T> Where<TCollection<T>>(this TCollection<T> sourceCollection, Expression<Func<T, bool>> expr)
        where TCollection : class, IEnumerable<T>, INotifyCollectionChanged
    {
        throw new NotImplementedException();
    }
}
1个回答

5

通用约束可能不完全符合您的要求,但这基本上是您要寻找的内容吗?这将限制TCollection为 IEnumerable<T>(尽管IEnumerable可以交换为List / Collection / Etc ...)

public static IEnumerable<T> Where<T, TCollection>(this TCollection sourceCollection, Expression<Func<T, bool>> expr)
where TCollection : IEnumerable<T>, INotifyPropertyChanged
{
    throw new NotImplementedException();
}

更新:我稍微修改了示例,以更好地遵循该方法 - 我之前有些困惑,没有意识到你想要一个 Where() 方法,我以为这是你的泛型约束 where


是的,那会起作用(单独使用)。我已经对那个签名进行了试验。不幸的是(可能对我而言),我正在尝试接近与System.Linq.Enumerable.Where扩展方法相同的签名(加上几个额外的限制——主要是INotifyCollecitonChanged)。 - Jason Jarrett
好的,虽然在我发帖到StackOverflow之前,我尝试了你在答案中给我的签名,但是无法让它正常工作...但最终我还是成功让它工作了。不管怎样,还是谢谢你 :) - Jason Jarrett
1
也许可以按照 Func<T1, TResult> 的模式(泛型参数在结果类型之前)使用 Where<TCollection, T> 而不是 Where<T, TCollection> - Sam Harwell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接