看起来您需要以下形式的数据结构:
public class SNode
{
public String Name { get; set; }
private readonly List<SNode> _Nodes = new List<SNode>();
public ICollection<SNode> Nodes { get { return _Nodes; } }
}
表单的序列化程序
public String Serialize(SNode root)
{
var sb = new StringBuilder();
Serialize(root, sb);
return sb.ToString();
}
private void Serialize(SNode node, StringBuilder sb)
{
sb.Append('(');
sb.Append(node.Name);
foreach (var item in node.Nodes)
Serialize(item, sb);
sb.Append(" )");
}
以及以下形式的反序列化器:
public SNode Deserialize(String st)
{
if (String.IsNullOrWhiteSpace(st))
return null;
var node = new SNode();
var nodesPos = String.IndexOf('(');
var endPos = String.LastIndexOf(')');
var childrenString = st.SubString(nodesPos, endPos - nodesPos);
node.Name = st.SubString(1, (nodesPos >= 0 ? nodePos : endPos)).TrimEnd();
var childStrings = new List<string>();
int brackets = 0;
int startPos = nodesPos;
for (int pos = nodesPos; pos++; pos < endPos)
{
if (st[pos] == '(')
brackets++;
else if (st[pos] == ')')
{
brackets--;
if (brackets == 0)
{
childStrings.Add(st.SubString(startPos, pos - startPos + 1));
startPos = pos + 1;
}
}
}
foreach (var child in childStrings)
{
var childNode = Deserialize(this, child);
if (childNode != null)
node.Nodes.Add(childNode);
}
return node;
}
但是,如果还没有测试甚至编译过这段代码,这或多或少是它可以工作的方式。