【问题标题】:Setting value to a not-existing array item?将值设置为不存在的数组项?
【发布时间】:2012-10-26 00:08:55
【问题描述】:

请看下面的代码:

Try
  Dim Reader As New System.IO.StreamReader(PositionsFileName)
  Do While Reader.Peek() <> -1
    Dim Positions() As String = Reader.ReadLine().Split("|")
    If (Positions(0) Is Nothing) Or (Positions(1) Is Nothing) Or (Positions(2) Is Nothing) Then
      ' something
    End If
  Loop
Catch ex As Exception
  ex.Source = Nothing
End Try

我正在读取一个文件并期待格式化某事|某事1|某事2。我试图将它设置为“Nothing”到不存在的数组索引(文件格式已损坏),以便 If 语句顺利进行,但似乎我做错了。能给我一些提示吗?

【问题讨论】:

  • 它会读多少“东西”?您可以执行 If Position.lenght() = 0 来了解拆分是否成功。
  • 您应该删除您的Catch ex As Exception。它并不能真正帮助您编写更好的代码,而只是隐藏错误。

标签: vb.net exception


【解决方案1】:

如果您执行Split("|") 并且只有2 个项目(例如something|something1),Positions(2) 将不是Nothing,它就不会存在。所以你的代码会引发一个异常,关于index out of bounds of the array

如果你需要Positions(2)在这种情况下包含Nothing,你的代码可以是这样的:

Dim Positions(2) As String
Dim tmpArray() As String = Reader.ReadLine().Split("|")
For i = 0 To UBound(Positions)
  If i <= UBound(tmpArray) Then
    Positions(i) = tmpArray(i)
  Else
    Positions(i) = Nothing
  End If
Next

【讨论】:

  • 这就是为什么我希望捕获该异常并将“Nothing”设置为 Position(2) 以使 If 语句失败。如何设置该值? ex.Source = Nothing 错了怎么办?
  • @barakuda28: ex.Source = Nothing 不会帮你设置Position(2) = Nothing。请参阅我的编辑以获取可能的解决方案。
【解决方案2】:

我假设每个有效行只有三个“Somethings”。如果是这样,请尝试像这样编写您的 Positions() 作业:

Dim Positions() As String = Reader _
    .ReadLine() _
    .Split("|") _
    .Concat(Enumerable.Repeat("Nothing", 3)) _
    .Take(3) _
    .ToArray()

这将确保您每次都拥有三个项目。无需检查任何内容。

【讨论】:

    【解决方案3】:

    只需在拆分后检查 position.length 即可。此外,如果您想检查诸如“||Something2|Something3”之类的情况,第一个位置将是“”而不是 Nothing。 orelse 是一个短路,如果满足较早的条件,它将阻止后一个条件被评估。

    If Positions.length < 3 OrElse Positions(0) = "" OrElse Positions(1) = "" OrElse Positions(2) = "" Then
      ' something
    End If
    

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2019-08-23
      • 2019-05-03
      相关资源
      最近更新 更多