VB.net - 'Property Chars: Is ReadOnly' 替换字符串字母时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14459424/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:58:49  来源:igfitidea点击:

VB.net - 'Property Chars: Is ReadOnly' error in replacing letter of a string

vb.net

提问by c3ntury

This private sub keeps telling me that 'Property Chars: Is ReadOnly'.

这个私人潜艇一直告诉我“属性字符:是只读的”。

Where have I gone wrong? StrWord is a string, e.g. 'banana'.

我哪里错了?StrWord 是一个字符串,例如'banana'。

What I was hoping it would do is loop through the word, and if the 'guess' (a single letter) matches any letter in the string (StrWord), it would replace it in the corresponding letter in the textbox of the word.

我希望它会循环遍历单词,如果“猜测”(单个字母)与字符串 (StrWord) 中的任何字母匹配,它就会将其替换为单词文本框中的相应字母。

So hangman, more or less.

所以刽子手,或多或少。

Thanks and regards,
Cameron.

谢谢和问候,
卡梅伦。

Private Sub Lookup(ByVal Guess)
    Dim Count As Integer = 0
    For Each Character As Char In StrWord
        If Character = Guess Then
            txtResult.Text(Count) = Guess
        Else
            Count += 1
        End If
    Next
End Sub

回答by tcarvin

Strings in .NET are immutable. That means you cannot change them. Instead, you need to create a new string and assign it to the Text property. You will find the System.Text.StringBuilderclass to be helpful as well, as it is mutable, and you can convert it into a String with the the ToStringmethod.

.NET 中的字符串是不可变的。这意味着你不能改变它们。相反,您需要创建一个新字符串并将其分配给 Text 属性。您会发现System.Text.StringBuilder该类也很有用,因为它是可变的,您可以使用该ToString方法将其转换为 String 。

Try something like this:

尝试这样的事情:

Private Sub Lookup(ByVal Guess As Char)

    Dim temp as new StringBuilder(txtResult.Text)

    Dim Count As Integer = 0
    For Each Character As Char In StrWord
        If Character = Guess Then
            temp.Chars(Count) = Character
        Else
            Count += 1
        End If
    Next
    txtResult.Text = temp.ToString()

End Sub

or this:

或这个:

Private Sub Lookup(ByVal Guess As Char)

Dim temp as new StringBuilder()

Dim Count As Integer = 0
For Each Character As Char In StrWord
    If Character = Guess Then
        temp.Append(Character)
    Else
        temp.Append("*")
        Count += 1
    End If
Next
txtResult.Text = temp.ToString()

End Sub

结束子

回答by David Brunow

Do you have the textbox set to ReadOnly to keep the user from modifying it? If so, you may need to change it from ReadOnly to make your change, then change it back to ReadOnly.

您是否将文本框设置为只读以防止用户修改它?如果是这样,您可能需要将其从只读更改为进行更改,然后将其更改回只读。

You could also try changing it this way:

您也可以尝试以这种方式更改它:

txtResult.Text.Replace(Character, Guess)