【问题标题】:how to recursively build treeview in c#如何在c#中递归构建树视图
【发布时间】:2010-09-22 15:25:00
【问题描述】:
private void enumerateValues(IEnumerator<KeyValuePair<string, object>> iEnumerator, TreeNode parentnode)
{
   if(iEnumerator is IEnumerable)
   {
     // ADD THE KEY
     TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Key);

     enumerateValues(iEnumerator.Current.Value, childNode);
   }
  else
   {
     /// add the value
     TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Value.ToString());
   }
}

我不知何故收到以下错误:

最佳重载方法匹配 'WindowsFormsApplication1.Form1.enumerateValues(System.Collections.Generic.IEnumerator>, System.Windows.Forms.TreeNode)' 有一些无效参数
参数 '1':无法从 'object' 转换为 'System.Collections.Generic.IEnumerator>'

请问怎么解决

【问题讨论】:

  • iEnumerator 将始终是 IEnumerable...您可能想在 if 子句中检查 iEnumerator.Current.Value

标签: c# recursion treeview


【解决方案1】:

下面这行很可能是罪魁祸首:

enumerateValues(iEnumerator.Current.Value, childNode);

因为enumerateValues 方法接受IEnumerator&lt;KeyValuePair&lt;string, object&gt;&gt;,所以键值对的值将始终为object 类型。因此您不能使用iEnumerator.Current.Value 调用该方法,因为该值不是IEnumerator&lt;KeyValuePair&lt;string, object&gt;&gt; 类型。

这正是错误消息告诉您的内容:

参数 '1':无法从 'object' 转换为 'System.Collections.Generic.IEnumerator>'

您必须先将iEnumerator.Current.Value 转换为正确的类型,然后才能调用该方法。您可以使用as operator 来执行此操作。

private void enumerateValues(IEnumerator<KeyValuePair<string, object>> iEnumerator, TreeNode parentnode)
{
  // Loop through the values.
  while (iEnumerator.MoveNext())
  {
    // Try a 'safe' cast of the current value.
    // If the cast fails, childEnumerator will be null.
    var childEnumerator = iEnumerator.Current.Value as IEnumerator<KeyValuePair<string, object>>;

    if (childEnumerator != null)
    {
      TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Key);

      enumerateValues(childEnumerator, childNode);
    }
    else
    {
      TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Value.ToString());
    }
  }
}

如果可以的话,我还建议您使用IEnumerable&lt;T&gt; 而不是IEnumerator&lt;T&gt;。它更清楚地显示了代码的意图,您不必手动处理迭代,您可以在上面使用LINQ

private void enumerateValues(IEnumerable<KeyValuePair<string, object>> items, TreeNode parentnode)
{
  foreach (var item in items)
  {
    // Try a 'safe' cast of the current value.
    // If the cast fails, childEnumerator will be null.
    var childEnumerator = item.Value as IEnumerable<KeyValuePair<string, object>>;

    if (childEnumerator != null)
    {
      TreeNode childNode = parentnode.Nodes.Add(item.Key);

      enumerateValues(childEnumerator, childNode);
    }
    else
    {
      TreeNode childNode = parentnode.Nodes.Add(item.Value.ToString());
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多