LearnGodot/Models/TreeNode.cs
2026-01-02 23:35:05 +08:00

73 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace Learn.Models;
public class TreeNode(Item item)
{
public class KeyValueInfo
{
public string Key { get; set; }
public string Value { get; set; }
public bool IsInherited { get; set; }
}
public TreeNode Parent => _parent;
public IEnumerable<TreeNode> Children => _children;
public Item Info => item;
private TreeNode _parent;
private readonly List<TreeNode> _children = new();
public void AddNode(TreeNode node)
{
if (_children.Contains(node)) return;
_children.Add(node);
node._parent = this;
}
public bool TryGetValue(string key, out string value, out bool isInherited)
{
value = null;
isInherited = false;
var curr = this;
bool valueExists = false;
while (curr.Info != null)
{
if (curr.Info.Info.TryGetValue(key, out var currValue))
{
value = currValue;
valueExists = true;
isInherited = (curr != this);
}
curr = curr.Parent;
}
return valueExists;
}
public IEnumerable<KeyValueInfo> GetKeyValueInfos()
{
var dict = new Dictionary<string, KeyValueInfo>();
var curr = this;
while (curr.Info != null)
{
foreach (var kv in curr.Info.Info)
{
var keyValueInfo = new KeyValueInfo
{
IsInherited = curr != this,
Key = kv.Key,
Value = kv.Value
};
dict[kv.Key] = keyValueInfo;
}
curr = curr.Parent;
}
return dict.Values.ToList();
}
}