gpt4 book ai didi

c# - 获取树中的所有 child

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:58 25 4
gpt4 key购买 nike

有一个存储元素树的类。子元素存放在

public List<BaseTreeData> Child { get; set; }

我想将这棵树显示为所有元素的“平面”(线性)列表。将类分成两个(基类和继承类)后,GetChildren 方法会生成有关类型不匹配的错误。很可能一切都是合乎逻辑的,但如何解决呢?

Error CS1503 Argument 1: cannot convert from 'ConsoleApplication1.BaseTreeData' to 'ConsoleApplication1.TreeData'

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var data = new List<TreeData>();
for (int i = 0; i < 5; i++)
{
var item = new TreeData() { Name = i.ToString() };
for (int j = 0; j < 3; j++)
{
var number = (i + 1) * 10 + j;
item.Child.Add(new TreeData() { ID = number, Name = number.ToString(), Parent = item });
}
data.Add(item);
}

foreach (var item in data.SelectMany(x => GetChildren(x)))
{
Console.WriteLine(item.ID + " " + item.Name + " " + item.IsChecked);
}
}

static IEnumerable<TreeData> GetChildren(TreeData d)
{
return new[] { d }.Concat(d.Child).SelectMany(x => GetChildren(x));
}
}

class BaseTreeData
{
public bool IsChecked { get; set; }
public BaseTreeData Parent { get; set; }
public List<BaseTreeData> Child { get; set; }

public BaseTreeData()
{
Child = new List<BaseTreeData>();
}
}

class TreeData : BaseTreeData
{
public int ID { get; set; }
public string Name { get; set; }
}
}

最佳答案

Error CS1503 Argument 1: cannot convert from 'ConsoleApplication1.BaseTreeData' to 'ConsoleApplication1.TreeData'

发生此错误是因为子节点是 BaseTreeData 而不是 TreeData

使用您发布的 BaseTreeData 类定义,childparent 将始终返回基类型。

相反,您可以使用泛型来解决这个问题,这样子节点将与父类具有相同的类型:

class BaseTreeData<T> where T : BaseTreeData<T>
{
public bool IsChecked { get; set; }
public T Parent { get; set; }
public List<T> Children { get; set; }

public BaseTreeData()
{
Children = new List<T>();
}

public IEnumerable<T> GetAncestors()
{
if (Parent == null)
yield break;

T relative = Parent;
while (relative != null)
{
yield return relative;
relative = relative.Parent;
}
}

public IEnumerable<T> GetDescendants()
{
var nodes = new Stack<T>();
nodes.Push(this as T);

while (nodes.Any())
{
var current = nodes.Pop();
yield return current;

foreach (var childNode in current.Children)
nodes.Push(childNode);
}
}
}

class TreeData : BaseTreeData<TreeData>
{
public int ID { get; set; }
public string Name { get; set; }
}

关于c# - 获取树中的所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com