[英]Option Strict On disallows implicit conversions from 'String' to 'Double'
[英]Option strict on disallows implicit conversion from string to double and double to string
我已經激活了Option Explicit
和Option Strict
,在我看來我得到了一些錯誤:
Option Strict On 不允許從 'String' 到 'Double' 的隱式轉換
和
Option Strict On 不允許從“Double”到“String”的隱式轉換。
為什么我會收到這些錯誤?
如果我刪除Option Strict
,我就沒有更多錯誤了。 有些錯誤可能無法修復,我該怎么辦? 如果發生這些錯誤,為什么要使用Option Strict
?
TxtCheckDraws.Text = TxtBoxIntDrawsCount.Text - 1
TxtCheckList.Text = TxtBoxIntDrawsCount.Text - 1
代碼:
Private Sub BttImport_Click(sender As Object, e As EventArgs) Handles BttImport.Click
TxtBoxIntDraws.Clear()
TxtBoxIntDraws.Text = System.IO.File.ReadAllText(My.Application.Info.DirectoryPath + ("\itemInfo.txt"))
Dim sr As New IO.StreamReader(My.Application.Info.DirectoryPath + ("\itemInfo.txt"))
Dim strLines() As String = Strings.Split(sr.ReadToEnd, Environment.NewLine)
TxtBoxIntDrawsCount.Text = strLines.Length
sr.Close()
TxtCheckDraws.Text = TxtBoxIntDrawsCount.Text - 1
TxtCheckList.Text = TxtBoxIntDrawsCount.Text - 1
TxtBoxIntDraws.Text = String.Join(Environment.NewLine, TxtBoxIntDraws.Lines.Select(Function(l) String.Join(",", l.Split(",").Select(Function(s) Integer.Parse(s)))))
End Sub
查看各個組件
TxtCheckDraws.Text = TxtBoxIntDrawsCount.Text - 1
TxtBoxIntDrawsCount
是一個文本框。 Text
屬性是一個字符串。 您嘗試從字符串中減去 1。 這個不對。 首先,將文本轉換為 integer。 以下將導致 integer。
Integer.Parse(TxtBoxIntDrawsCount.Text) - 1
我們有另一個 TextBox TxtCheckDraws
和另一個 Text 屬性,它也是一個字符串。 我們不能將 integer Integer.Parse(TxtBoxIntDrawsCount.Text) - 1
分配給字符串。 所以我們應該先把它轉換回字符串。
TxtCheckDraws.Text = (Integer.Parse(TxtBoxIntDrawsCount.Text) - 1).ToString()
只要TxtBoxIntDrawsCount
中確實有 integer ,它就可以工作。 例如,如果它有字符串“four”而不是字符串“4”,那么您將遇到問題。 您將需要添加一些驗證。 有很多方法可以做到這一點,它們不在問題的 scope 范圍內。
Option Explicit On
強制您聲明所有變量。 Option Strict On
強制您明確指定轉換。 根據期權嚴格聲明:
當文件中出現 Option Strict On 或 Option Strict 時,以下情況會導致編譯時錯誤:
- 隱式縮小轉換
- 后期裝訂
- 導致 Object 類型的隱式鍵入
這樣做的好處是,它產生的代碼明確地說明了程序員的想法。 您仍然可以執行隱式擴展轉換。 例如,從Integer
到Double
的隱式轉換仍然有效。
將您的代碼更改為
TxtCheckDraws.Text = (CInt(TxtBoxIntDrawsCount.Text) - 1).ToString()
TxtCheckList.Text = (CInt(TxtBoxIntDrawsCount.Text) - 1).ToString()
這清楚地表明您想要將文本框的內容解釋為Integer
,然后想要從中減去1
,最后想要將結果轉換回String
。
使用Integer.TryParse
也是一個好主意,以防用戶輸入無效數字
Dim number As Integer
If Integer.TryParse(TxtBoxIntDrawsCount.Text, number) Then
TxtCheckDraws.Text = (number - 1).ToString()
Else
' Tell the user to enter a correct number
End If
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.