【问题标题】:Generic Class Inheritence and LINQ Extension Methods泛型类继承和 LINQ 扩展方法
【发布时间】:2011-11-18 18:00:31
【问题描述】:

假设我有一个看起来像这样的通用类

public class GenericCollection<T> : Collection<T>, IQueryable<T>
{
    public string SomeCollectionProperty { get; set; }

    ...
    // IQueryable implentations
}

现在我有了上述父类的子类

public class SomeCollection : GenericCollection<SomeType>
{
    // Some Additional Functionality here
}

在泛型类中,我充分利用了 LINQ 扩展方法(例如 Where、First、Select 等)

当我尝试访问派生类中的 LINQ 扩展方法时,它似乎忘记了它是 IQueryable 或 IEnumerable

我希望它会做这样的事情(在 SomeCollection 中)

public SomeType FindFirst(int SomeProperty)
{
    return this.First(t => t.someproperty == SomeProperty);
}

但是当我点击 .在这个视觉工作室没有给我任何扩展方法之后

我绞尽脑汁想弄明白为什么

特别是因为如果在我的 Generic 类中,我只是从 Collection&lt;T&gt; 继承,它实现了 IEnumerable&lt;T&gt;,它具有与之关联的 LINQ 扩展方法,我仍然可以在我的泛型类中使用 LINQ 扩展方法,但只要我定义了一个强基于我的泛型类的类型化类我失去了 LINQ 扩展方法

我希望我不只是让每个人都感到困惑,因为我确实觉得自己很困惑

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    我的猜测是它找不到扩展方法,因为您可能需要:

    using System.Linq;
    

    这应该在你的子类中。

    【讨论】:

    • sigh 当然我会想念 OBVIOUS 这就是我认为我所有的课程都有相同的 using 声明集感谢白痴检查:-)
    • @Tofu,这发生在我们所有人身上。 :)
    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多