【问题标题】:Why do i get: "Error 2 Argument 1: cannot convert from 'int' to 'TRAINING1.Node<int>' " error?为什么我会得到:“错误 2 参数 1:无法从 'int' 转换为 'TRAINING1.Node<int>'”错误?
【发布时间】:2013-04-17 13:28:19
【问题描述】:

这是一个应该获取列表并将其反转的函数。我不知道为什么会出现这个错误。

    public static void What(List<int> lst)
    {
        Stack<int> st1 = new Stack<int>();
        while (!lst.IsEmpty())
        {
            **st1.Push(lst.Remove(lst.GetFirst().GetInfo());**
        }
        Node<int> pos = lst.GetFirst();
        while (!st1.IsEmpty())
        {
            pos = lst.Insert(pos, st1.Pop());
        }
    }

【问题讨论】:

  • .GetInfo() 返回什么?
  • 什么是方法:GetFirst() 和 .GetInfo() ? - 我假设他们不返回一个 int?
  • 您将 pos 作为第一个参数传递给 lst.Insert 方法。该参数应该是一个 int 而不是一个 Node 这就是 pos 。

标签: c# list class stack


【解决方案1】:

st1 是一个Stack&lt;int&gt;,这意味着它是一个强类型的整数堆栈。如果没有从Node&lt;int&gt;int 的隐式转换,则不能将Node&lt;int&gt; 添加到此列表中。无论如何,尝试使用下一个代码作为使用堆栈的示例:

public static void Reverse(List<int> lst)
{
   Stack<int> st1 = new Stack<int>();
   while (lst.Count != 0)
   {
        var item = lst[0];
        lst.RemoveAt(0);
        st1.Push(item);
   }
   while (st1.Count != 0)
   {
       lst.Add(st1.Pop());
   }
}

这不是一个有效的解决方案,并且有很多缺点。我只想说明使用堆栈的正确反转方法尽可能接近您的情况。

您可以将方法 Reverse 设为通用,但在 Linq 中已经实现了这些行为。

考虑使用Reverse Linq 方法。如果您只想反转List&lt;int&gt;,请使用myList.Reverse().ToList()。它将返回相同的List&lt;int&gt;,但顺序相反。

【讨论】:

  • + 1 表示反向 Linq 方法
  • 不需要第一个循环。 Stack&lt;int&gt; st1 = new Stack&lt;int&gt;(lst); lst.Clear();就够了
  • @I4V 是的,谢谢,我知道。我想让正确的行为接近 OPs 问题。也无需指定int。只需使用new Stack&lt;T&gt;(lst); lst.Clear(); 并制作Reverse&lt;T&gt; (List&lt;T&gt; lst)
  • 感谢大家的评论:) GetInfo() 应该返回节点中的信息 - 一个 int。为什么它不能这样工作?如何让计算机识别节点的 int 并在其上使用 st1.Push(...)?(在错误行中:st1.Push(lst.Remove(lst.GetFirst(). GetInfo());)
猜你喜欢
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2013-12-15
相关资源
最近更新 更多