VB.NET - 想要将两个可空类型加在一起 ​​- 如何? (即 var1 + var2 两者都可为空且 vari1=Nothing,Var2=5 结果为 Nothing)

发布于 2024-09-16 10:19:29 字数 482 浏览 2 评论 0原文

我有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮生面具三千个 2024-09-23 10:19:29
nVar1.GetValueOrDefault()+ nVar2.GetValueOrDefault()

或者在 C# 中:

(nVar1??0)+(nVar2??0)
nVar1.GetValueOrDefault()+ nVar2.GetValueOrDefault()

Or in c#:

(nVar1??0)+(nVar2??0)
紫﹏色ふ单纯 2024-09-23 10:19:29

我认为最简单的方法是使用 If 运算符将 Nothing 值强制转换为默认值。

nVarSum = If(nVar1,0) + If(nVar2,0)

当应用于可为空类型时,2 个参数形式的 If 运算符本质上执行以下操作。如果可为 null 的值有值,则返回的是该值,否则返回的是第二个参数。

I think the simplest way is to use the If operator to coerce Nothing values into a default one.

nVarSum = If(nVar1,0) + If(nVar2,0)

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.

不气馁 2024-09-23 10:19:29

或者明确地不进行任何测试并设置默认值。与发布的其他答案相同的结果。

If nVar1 is nothing then
   nVar1 = 0
end if

nVarSum = nVar1 + nVar2

Or explicitly test for nothing and set your default value. Same result as other answers posted.

If nVar1 is nothing then
   nVar1 = 0
end if

nVarSum = nVar1 + nVar2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文