简体   繁体   English

如何替换VB.NET中List(Of String)中的项?

[英]How do I replace an item in List(Of String) in VB.NET?

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? 有人可以帮我一把吗?

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 答案A.

Answer C 答案C.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM