我有一门课,使嵌套分组。简化形式如下。
public class Group
{
public readonly object Key;
public readonly IEnumerable<Group> Groups;
public readonly IEnumerable<DataRow> Drs;
public Group(object key, IEnumerable<DataRow> source, List<string> columnList)
{
Key = key;
if (columnList.Count == 0)
Drs = source;
else
{
string firstColumn = columnList.First();
List<string> restOfColumns = columnList.Skip(1).ToList();
Groups = source.GroupBy(dr => dr[firstColumn])
.Select(g => new Group(g.Key, g, restOfColumns));
}
}
}
在某种程度上,这是可以的。但是有时我需要为此类提供更多属性(和方法)。同时,我不想将这些属性添加到此类中,因为这将破坏简单性,并且大多数用法对这些属性将不感兴趣。因此,我尝试从此类继承。
public class SpecialGroup:Group
{
public SpecialGroup(object key, IEnumerable<DataRow> source, List<string> columnList)
: base(key, source, columnList)
{
}
public void DoSomething()
{
// do something
}
}
但是这一次
SpecialGroup
并不是递归生成的(如预期的那样)。只有第一个主组是SpecialGroup
,嵌套组都是Group
。我可以通过某种方式从
Group
继承而仍然具有新类型的递归吗?(请不要使用扩展方法,因为这与在
Group
类中编写所有方法没有什么不同) 最佳答案
您可以更改组多态的创建。例如:
public class Group
{
public readonly object Key;
public readonly IEnumerable<Group> Groups;
public readonly IEnumerable<DataRow> Drs;
public Group(object key, IEnumerable<DataRow> source, List<string> columnList)
{
Key = key;
if (columnList.Count == 0)
Drs = source;
else
{
string firstColumn = columnList.First();
List<string> restOfColumns = columnList.Skip(1).ToList();
Groups = source.GroupBy(dr => dr[firstColumn])
.Select(g => CreateGroup(g.Key, g, restOfColumns));
}
}
protected virtual Group CreateGroup(object key, IEnumerable<DataRow> source, List<string> columnList)
{
return new Group(key, source, columnList)
}
}
然后在您的
SpecialGroup
中覆盖它以返回SpecialGroup
。public class SpecialGroup:Group
{
public SpecialGroup(object key, IEnumerable<DataRow> source, List<string> columnList)
: base(key, source, columnList)
{
}
public void DoSomething()
{
// do something
}
protected override Group CreateGroup(object key, IEnumerable<DataRow> source, List<string> columnList)
{
return new SpecialGroup(key, source, columnList)
}
}
这样,如果您的根组的类型为
SpecialGroup
,则其子组的类型将为SpecialGroup
,否则为Group
。