字符串拆分函数的 System.NullreferenceException [duplicate]

System.NullreferenceException for String split function [duplicate]

提问人:zwheeler 提问时间:4/6/2023 最后编辑:John Alexiouzwheeler 更新时间:4/6/2023 访问量:58

问:

我是 C# 的新手,正在修改我的第一个大程序。我不断得到以下内容,我不确定如何更新它,您的帮助将不胜感激

baseErrorCodes = New List(Of String)()
Dim errorCodeDescription As String = String.Empty
Dim baseCode As String
For Each errorCode As String In errorCodes
    Dim matchingBusinessRuleByResponseCode As BusinessRule = Me.DomainData.Common.BusinessRules _
        .FirstOrDefault(Function(businessRule) (businessRule.ApplicationSource = Me.BusinessRuleSource _
                                OrElse businessRule.ApplicationSource = "Maryland") _
                            AndAlso businessRule.ResponseCode = errorCode)

    baseCode = errorCode.Split("-")(0)
    If (matchingBusinessRuleByResponseCode IsNot Nothing) Then
        If (String.IsNullOrWhiteSpace(fieldSource)) Then
            fieldSource = matchingBusinessRuleByResponseCode.FieldSource
        End If

错误信息

Error Message

.NET vb.net 异常 null 系统

评论

0赞 zwheeler 4/6/2023
error 是 baseCode = errorCode.Split
1赞 David 4/6/2023
这不是 C# 这一事实可能是您困惑的一部分?

答:

0赞 John Alexiou 4/6/2023 #1

所以是空的。这是未找到匹配项的结果,字符串类型的默认值为 null。这是 的预期行为。errorCode.FirstOrDefault()

要解决此问题,请在调用 之前添加检查。If errorCode IsNot null Then ....Split()

或用于处理。String.IsNullOrEmpty()