VB.NET - 想要将两个可空类型加在一起 - 如何? (即 var1 + var2 两者都可为空且 vari1=Nothing,Var2=5 结果为 Nothing)
我有:
Dim nVar1 As Long?
Dim nVar2 As Long?
Dim nVarSum As Long?
nVar1 = Nothing
nVar2 = 5
nVarSum = nVar1 + nVar2
我希望结果以 nVarSum 为 5 结束,而不是无。
我知道如果你添加一些东西到一个未知的值,你最终会得到“东西+未知”或 x+5 将始终等于“x+5”而不是“5”,因为您仍然携带着未知的“x”。
但是,在这种情况下,为了加法的目的,如何有效地将未知或无视为零?
谢谢!
(基本上发生的事情是最终用户向我们发送一个数据文件,此代码解析该文件,然后将大约 15 个字段加在一起。如果用户将这些字段留空而不是为其分配零,我需要对其进行处理就好像这一次加法操作的值为零一样,但所有其余代码需要继续将其视为 Nothing 值,因为用户实际上并未提交零...他们提交了空白或什么都没有)
I have:
Dim nVar1 As Long?
Dim nVar2 As Long?
Dim nVarSum As Long?
nVar1 = Nothing
nVar2 = 5
nVarSum = nVar1 + nVar2
I would prefer the result to end with nVarSum being 5, instead of Nothing.
I understand if you add something to an unknown value, you will end up with "somthing + unknown" or
x+5 will always equal "x+5" not "5" because you are still carrying around that unknown "x".
However, how can I effectively treat an unknown or Nothing as a zero for the purposes of addition in this case?
Thanks!
(What is basically happening is that the end user is sending us a data file, this code parses that file and then sums together about 15 fields. If the user leaves those fields blank instead of assigning a zero to them, I need to treat it as if it was a zero for this one addition operation, but all the rest of the code needs to continue seeing it as a Nothing value since the user did not ACTUALLY submit zero... they submitted blank or nothing)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者在 C# 中:
Or in c#:
我认为最简单的方法是使用
If
运算符将Nothing
值强制转换为默认值。当应用于可为空类型时,2 个参数形式的
If
运算符本质上执行以下操作。如果可为 null 的值有值,则返回的是该值,否则返回的是第二个参数。I think the simplest way is to use the
If
operator to coerceNothing
values into a default one.The
If
operator in the 2 argument form when applied to nullable types essentially does the following. If the nullable has a value then the return is the value, otherwise it's the second argument.或者明确地不进行任何测试并设置默认值。与发布的其他答案相同的结果。
Or explicitly test for nothing and set your default value. Same result as other answers posted.