【发布时间】:2017-12-14 13:33:11
【问题描述】:
如果我实例化我的List<string> 的子类,那么我可以使用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<string>”不包含“选择”的定义。
为什么会出现这种情况,是否有解决方法?
【问题讨论】:
-
从
List<T>继承通常没有太多好的理由,您确定这是满足您需求的最佳方式吗? -
@maccettura,我这样做是因为我想添加可以充当过滤器的属性——Linq 逻辑的简写代码。我正在编写的代码将被团队使用,可读性非常重要。有没有更好的方法来达到同样的目的?
-
听起来您可能需要字典而不是列表。字典不能有重复的键,如果你尝试它会抛出异常。此外,您应该创建一个具有私有 Dictionary 或 List 作为数据存储的类,然后通过方法或属性公开日期(在那里进行过滤)
-
@maccettura 这很有意义。感谢您的提示!