vb.net string() 类型的值不能转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45725431/
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
Value of type string() cannot be converted to string
提问by William Juden
I keep getting this error, I tried all I could but it still says "Value type of String() cannot be converted to string."
我一直收到这个错误,我尽我所能,但它仍然说“String() 的值类型不能转换为字符串。”
Here is the code:
这是代码:
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Sub New()
InitializeComponent()
RAN = New Random
WB = New WebClient
End Sub
Private Const IDNum As String = "https://example.com/Data.php"
Private WB As WebClient
Private RAN As Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Account As String() = WB.DownloadString(IDNum).Split(Environment.NewLine)
AccSplit(Account(RAN.Next(1, Account.Length)))
End Sub
Private Sub AccSplit(ByVal Account As String)
TextBox2.Text = Account.Split()
End Sub
回答by jmcilhinney
When you call Splithere:
当你Split在这里打电话时:
TextBox2.Text = Account.Split()
You are getting a Stringarray back. Calling Splitwith no arguments will split the Stringon whitespace characters. For instance, this:
你得到一个String数组。Split不带参数的调用将拆分String空白字符。例如,这个:
Dim arr = "Hello World".Split()
is equivalent to this:
相当于:
Dim arr = {"Hello", "World"}
The Textproperty of a TextBoxis type String, so you can't assign a Stringarray to it. That doesn't make sense. If you want to fry an egg, do you put am egg carton in the pan? The correct course of action depends on what you're actually trying to achieve. If you just want that Stringdisplayed in the TextBoxthen do this:
a 的Text属性TextBox是 type String,因此您不能为其分配String数组。那没有意义。如果你想煎鸡蛋,你把鸡蛋盒放在锅里吗?正确的行动方针取决于您实际想要达到的目标。如果您只想String显示在 中,TextBox请执行以下操作:
TextBox2.Text = Account
You could also do this:
你也可以这样做:
TextBox2.Lines = Account.Split()
to display the array with the elements on separate lines in the TexTbox, which assumes that you have set its Multilineproperty to True.
以在 中的单独行上显示具有元素的数组TexTbox,假设您已将其Multiline属性设置为True。
回答by Joel Coehoorn
TextBox2.Textis a string. The string.Split()function returns an arrayof strings (shown by Visual Studio as a string()). Those types don't match up. You can't just assign an array to a string. I might ask if you wanted this:
TextBox2.Text是一个字符串。该string.Split()函数返回一个字符串数组(在 Visual Studio 中显示为string())。这些类型不匹配。您不能只将数组分配给字符串。我可能会问你是否想要这个:
TextBox2.Text = String.Join(",", Account.Split())
That will at least compile. But it makes no sense... why split a string, just to join it back again?
那至少会编译。但这没有任何意义......为什么要拆分一个字符串,只是为了再次连接它?

