【问题标题】:Why can't I use Linq Select in subclass of List<string> using base.Select? [duplicate]为什么我不能使用 base.Select 在 List<string> 的子类中使用 Linq Select? [复制]
【发布时间】:2017-12-14 13:33:11
【问题描述】:

如果我实例化我的List&lt;string&gt; 的子类,那么我可以使用Linq 的Select 方法。

using System.Linq;

namespace LinqProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            BetterList list = new BetterList();
            list.Select(l => l.ToString() == "abc");  // no compile error
        }
    }
}

但是如果我尝试在子类的定义中使用 Select...

using System.Collections.Generic;
using System.Linq;

namespace LinqProblem
{
    class BetterList : List<string>
    {
        public List<string> Stuff
        {
            get
            {
                base.Select(l => l.ToString() == "abc");  // compile error
            }
        }
    }
}

错误:

List&lt;string&gt;”不包含“选择”的定义。

为什么会出现这种情况,是否有解决方法?

【问题讨论】:

  • List&lt;T&gt;继承通常没有太多好的理由,您确定这是满足您需求的最佳方式吗?
  • @maccettura,我这样做是因为我想添加可以充当过滤器的属性——Linq 逻辑的简写代码。我正在编写的代码将被团队使用,可读性非常重要。有没有更好的方法来达到同样的目的?
  • 听起来您可能需要字典而不是列表。字典不能有重复的键,如果你尝试它会抛出异常。此外,您应该创建一个具有私有 Dictionary 或 List 作为数据存储的类,然后通过方法或属性公开日期(在那里进行过滤)
  • @maccettura 这很有意义。感谢您的提示!

标签: c# .net linq


【解决方案1】:

Select() 是一种扩展方法。 base关键字专门用于非虚调用基类方法,不支持扩展方法。

把它改成this.Select就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2012-10-03
    • 2019-06-28
    • 2014-04-04
    相关资源
    最近更新 更多