You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET开启Option Strict On时&运算符报错的解决方法

解决Option Strict On下的VB.NET类型转换错误

当开启Option Strict On时,VB.NET会强制要求显式类型转换,不允许隐式的Object到String转换。原代码中DataGridView1.SelectedRows(0).Cells(0).Value返回的是Object类型,直接与String.Empty拼接会触发类型不匹配错误,以下是几种在保持Option Strict On开启的前提下消除错误的方法:

  • 方法一:使用VB.NET内置的CStr()函数显式转换
    CStr()会将Object类型值转换为String,若值为Nothing则返回空字符串:

    Dim Invno As String = CStr(DataGridView1.SelectedRows(0).Cells(0).Value) & String.Empty
    
  • 方法二:使用Convert.ToString()方法(推荐,更安全)
    该方法属于.NET框架通用方法,能安全处理null(VB.NET中为Nothing)的情况,直接返回空字符串,无需额外拼接String.Empty:

    Dim Invno As String = Convert.ToString(DataGridView1.SelectedRows(0).Cells(0).Value)
    
  • 方法三:结合ToString()与空值判断
    若要使用对象的ToString()方法,需先判断值是否为Nothing,避免抛出NullReferenceException:

    Dim cellValue As Object = DataGridView1.SelectedRows(0).Cells(0).Value
    Dim Invno As String = If(cellValue Is Nothing, String.Empty, cellValue.ToString())
    

内容的提问来源于stack exchange,提问作者roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:31:00