Newbie到C#这里。在我的代码中,我想构建一个字符串列表,然后稍后将第一个元素从列表的最前面弹出:
1 public class foo
2 {
3 public List<String> listo;
4
5 public foo()
6 {
7 this.listo = new List<String>();
8 listo.Add("Apples");
9 listo.Add("Oranges");
10 listo.Add("Bananas");
11 RemoveAndPrintAll();
12 }
13
14 public void RemoveAndPrintAll()
15 {
16 while(listo.Count > 0)
17 {
18 System.Console.WriteLine(this.listo.RemoveAt(0));
19 }
20 }
21 }
MS Visual Studio告诉我,第18行有一个语法错误,特别是此部分:
this.listo.RemoveAt(0)
错误是,没有非常有用的描述:
参数'数字'不能从键入转换为typeb
一种方法中一个参数的类型与
当班级实例化时通过。这个错误通常会出现
以及CS1502。有关如何解决此问题的讨论,请参见CS1502
错误。
cs1502
当参数类型传递给方法时,会发生此错误
不匹配该方法的参数类型。如果称为方法
被超载,然后没有一个超载版本具有签名
与正在传递的参数类型相匹配。
那怎么了?问题的根源是:
- 我创建一个列表,然后用字符串填充它
- ,我尝试从列表中删除字符串...只有编译器不再认为元素是字符串。
如果我需要在这里做一些特别的事情?为什么编译器在删除列表时不识别元素的数据类型?谢谢
newbie to C# here. In my code, I want to build a list of strings, then later pop the first element off the front of the list:
1 public class foo
2 {
3 public List<String> listo;
4
5 public foo()
6 {
7 this.listo = new List<String>();
8 listo.Add("Apples");
9 listo.Add("Oranges");
10 listo.Add("Bananas");
11 RemoveAndPrintAll();
12 }
13
14 public void RemoveAndPrintAll()
15 {
16 while(listo.Count > 0)
17 {
18 System.Console.WriteLine(this.listo.RemoveAt(0));
19 }
20 }
21 }
MS Visual Studio tells me that line 18 has a syntax error, specifically this part:
this.listo.RemoveAt(0)
The error is CS1503, which doesn't have a very helpful description:
Argument 'number' cannot convert from TypeA to TypeB
The type of one argument in a method does not match the type that was
passed when the class was instantiated. This error typically appears
along with CS1502. See CS1502 for a discussion of how to resolve this
error.
CS1502 is vaguely helpful:
This error occurs when the argument types being passed to the method
do not match the parameter types of that method. If the called method
is overloaded, then none of the overloaded versions has a signature
that matches the argument types being passed.
So what the heck? The root of the problem is this:
- I create a List, then populate it with Strings
- Later, I try to remove Strings from the list... only the compiler doesn't think the elements are Strings any more.
If there something special I need to do here? Why would the compiler not recognize the elements' data type when it comes time to remove them from the list? Thank you
发布评论
评论(2)
在您的代码中,
将从列表中删除0个元素。它不会删除所有元素。
作为一个简单的测试,您可以使用此代码进行测试:
您可以执行此操作;
对于推送和流行功能,请使用堆栈。
In your code,
will remove the 0th element from the list. It won't remove all elements.
As a simple test, you can use this code to test:
You can do this;
For push and pop functionality, use Stack however.
不返回任何内容(它具有
void
返回类型)。您需要像这样删除之前获取第一个元素,请考虑使用 stack&lt; t&gt; 而不是
list&lt; t&gt;
as @yassinmi指出。List<T>.RemoveAt(index) does not return anything (it has
void
return type). You will need to get the first element before removing it likeThat said, consider using Stack<T> instead of
List<T>
as @yassinmi pointed out.