Option Strict 和 Nulls [英] Option Strict and Nulls
问题描述
我不希望数据库中有空字符串.当一个字段为空时,我希望它为空.我正在尝试替换
I do not want empty strings in the database. When a field is null, I want it to be null. I am trying to replace
If strStreet = "" Then
cmd.Parameters("@Street").Value = DBNull.Value
Else
cmd.Parameters("@Street").Value = strStreet
End If
使用 VB If 运算符如下
with the VB If Operator as follows
cmd.Parameters("@Street").Value = If(strStreet = "", DBNull.Value, strStreet)
我从第一个 = 符号右侧所有内容下方的红色波浪线中收到以下消息.无法推断通用类型,并且 Option Strict On 不允许假设 'Object'."好的,所以我做了一个小演员
I get the following message from the red squiggly under everything to the right of the first = sign. "Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed." OK, so I do a little cast
cmd.Parameters("@Street").Value = If(strStreet = "", CObj(DBNull.Value), strStreet)
红色波浪线消失,CObj 下方出现绿色波浪线,表示多余演员.我是不是该A. 关闭 Option StrictB. 忽略绿色波浪线C. 回到我的 If...Else...End If或者是其他东西??顺便说一句,当我为某些控件的 Text 属性准备字符串时,它在另一个方向上效果很好.
The red squiggly disappears and a green squiggly appears under CObj saying redundant Cast. Should I A. Turn off Option Strict B. Ignore the green squiggly C. Go back to my If...Else...End If or something else?? BTW it works great in the other direction when I am preparing a string for the Text property of some control.
strStreet = If(reader.GetValue(2) IsNot DBNull.Value, reader.GetString(2), "")
我在这里阅读了几个围绕我的问题的问题和答案,但我不太明白.感谢您的关注.
I have read several question and answers here that are circling my problem but I can't quite get it. Thank you for your kind attention.
推荐答案
不确定究竟是什么触发了 redundant cast 警告,但是使用以下扩展方法,您不应该收到警告,并且参数多,代码少.
Not sure what exactly is triggering the redundant cast warning, but with the following extension method you shouldn't get a warning and also have less code if there are many parameters.
Imports System.Runtime.CompilerServices
Module Extensions
<Extension>
Public Function GetDBNullIfEmpty(s As String) As Object
If String.IsNullOrEmpty(s) Then
Return DBNull.Value
Else
Return s
End If
End Function
End Module
然后你可以像这样设置你的参数值:
then you can set your parameter-value like this:
cmd.Parameters("@Street").Value = strStreet.GetDBNullIfEmpty
这篇关于Option Strict 和 Nulls的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!