如何在 VB.NET 中替换 List(Of String) 中的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25090837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace an item in List(Of String) in VB.NET?
提问by Chris Shula
I am having issues with one of my projects. In it, I am facing the obstacle of indexing problems. I have a list instantiated this way:
我的一个项目有问题。在其中,我面临着索引问题的障碍。我有一个以这种方式实例化的列表:
Public answers As List(Of String) = New List(Of String)
Items are added to this list by this code:
通过以下代码将项目添加到此列表中:
Dim correctanswer As String = "" 'except the user changes the value with the GUI
frmMain.answers.Add(correctanswer)
(And by the way, I'm only including the relevant parts to this monster of a project, so I will post more code by request, if needed.)
(顺便说一句,我只包含了这个项目怪物的相关部分,所以如果需要,我会根据要求发布更多代码。)
This code works fine; however, I am attempting to allow the user to modify each list item at will. I tried doing that by the following method:
这段代码工作正常;但是,我试图允许用户随意修改每个列表项。我尝试通过以下方法做到这一点:
frmMain.answers.ElementAt(i) = correctanswer '(where 'i' is the index in question)
and the compiler doesn't like that. It's yelling at me.
编译器不喜欢那样。它在对我大喊大叫。
Expression is not a value and therefore cannot be the target of an assignment.
表达式不是值,因此不能成为赋值的目标。
Now, I've faced this issue before when I was trying to replace items in a similar list; however, those items were my own custom classes. This is just a list of strings. I tried another method as well:
现在,我之前在尝试替换类似列表中的项目时遇到过这个问题;然而,这些项目是我自己的自定义类。这只是一个字符串列表。我也尝试了另一种方法:
frmMain.RemoveAt(i)
frmMain.Insert(i, correctanswer)
The problem with that is, the order of the list gets mixed up. The indexes move around, and it ultimately makes a mess rather than doing what I want it to.
问题在于,列表的顺序会混淆。索引四处移动,最终弄得一团糟,而不是按照我的意愿行事。
Can someone please give me a hand?
有人可以帮我一把吗?
回答by Pete
frmMain.answers(i) = correctanswer
frmMain.answers(i) = correctanswer
Here is a small example:
这是一个小例子:
Dim answers As List(Of String) = New List(Of String)
answers.Add("Answer A")
answers.Add("Answer B")
answers.Add("Answer C")
Dim correctanswer As String = ""
answers(1) = correctanswer
For Each str As String In answers
Console.WriteLine(str)
Next
This should print:
这应该打印:
Answer A
Answer C
答案 A
答案 C

