VB.NET 赋值中的双重赋值有何作用?

发布于 2024-09-10 08:20:33 字数 512 浏览 4 评论 0原文

我(VB.NET 新手)正在对一个函数进行一些代码维护,该函数有时会抛出异常“将字符串“False”(或“True”)转换为 Integer 类型时出错”。我发现与此 someVal 等效的

是一个字符串,someFun1 返回一个整数,而 someFun2 将一个整数作为参数

...
someVal = someVal = someFun1()
...
someFun2(someVal)
...

我认为可能发生的情况是它试图将 someFun1 的返回值分配给 someVal,然后执行布尔检查是否 someVal 已经改变 - 但我不认为这是需要做的。

我的问题是 - 这个双重赋值 (someVal = someVal = someFun1()) 是否完成了我在 VB.NET 中不知道的任何事情?

另一个注意事项:我意识到存在整数到字符串再返回整数的隐式转换,但这不会导致任何问题,因为这些值应该始终保存一个数值(可以从整数和字符串隐式来回转换) ,对吧?)不是对或错 - 据我所知

I (new to VB.NET) am doing some code maintenance on a function that sometimes throws an exception "error converting string "False" (or "True") to type Integer." What I found was something equivalent to this

someVal is a string, someFun1 returns an Integer and someFun2 takes an Integer as a parameter

...
someVal = someVal = someFun1()
...
someFun2(someVal)
...

What I think might be happening is that it is trying to assign someFun1's return value into someVal, then perform a bool check as to whether someVal has changed - but I don't think that is what needs to be done.

My question is - does this double assignment (someVal = someVal = someFun1()) accomplish anything that I don't know about in VB.NET?

another note: I realize there are implicit casts of integer to string and back to integer, but that shouldn't be causing any problems, because the values should always hold a numerical value (which can be implicitly cast back and forth from Integer and String, right?) not True or False - as far as I can tell

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

心意如水 2024-09-17 08:20:33

这里令人困惑的是,等于运算符 = 与 VB.NET 中的赋值运算符 = 相同。在 C# 中,上面的代码相当于

someVal = someVal == someFun1();

首先执行布尔等于运算符 ==,然后将结果插入到 someVal 中。这会失败,因为 someValint,而不是 bool

换句话说,运行时将 someValsomeFun1() 的返回值进行比较,返回 TrueFalse ,并且未能将其转换为整数。这不是“双重赋值” - 它只是一种内联表示,

If someVal = someFun1() Then
    someVal = True
Else
    someVal = False
End If

更明显的是我们试图为 Integer 变量提供 Boolean

The confusion here is that the equals operator = is the same as the assignment operator = in VB.NET. In C#, the code above would be equivalent to

someVal = someVal == someFun1();

where the boolean equals operator == is carried out first, and the result is inserted into someVal. This fails, because someVal is int, not bool.

In other words, the runtime is comparing someVal with the return value of someFun1(), returning True or False, and failing to cast that to an integer. This isn't a "double assignment" - it's just an inline representation of

If someVal = someFun1() Then
    someVal = True
Else
    someVal = False
End If

where it is much more obvious that we're trying to give an Integer variable a value of type Boolean.

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