为什么还要编译这些代码? [英] Why does this code even compile?

查看:50
本文介绍了为什么还要编译这些代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:
为什么下面的代码(不是我写的)甚至可以编译?
我的意思是,除了选项strict禁用和选项推断处于打开状态之外……

Question:
Why does the below code (not written by me) even compile ?
I mean apart from the fact that option strict is off and option infer is on...

If Not actdate.DayOfWeek = DayOfWeek.Saturday And Not actdate.DayOfWeek.Sunday Then
...
End If

****
对于那些不精通VB的人,它显然与以下内容相同:

if (!(actdate.DayOfWeek == DayOfWeek.Saturday) & !actdate.DayOfWeek.Sunday) {
...
}

基本上已经回答了这个问题,因为要记住的是VB-`AND`实际上是按位与.

推荐答案

接受的答案不正确,VB.NET中的运算符优先级确保使用And运算符的逻辑版本,与AndAlso相同.由于使用了Not运算符,因此左侧和右侧操作数均为Boolean类型.VB.NET中的优先级是关系>不>和.在C#中是!>关系>&.或者换一种说法,您不需要像在C#中那样在VB.NET中使用括号.

The accepted answer is not correct, operator precedence in VB.NET ensures that the logical version of And operator is used, same one as AndAlso. Both the left-hand and right-hand operands are of type Boolean thanks to the Not operators being used. Precedence in VB.NET is relational > Not > And. In C# it is ! > relational > &. Or to put it another way, you don't need parentheses in VB.NET like you do in C#.

Visual Basic中的Not运算符接受布尔或数字表达式.就像C#中一样,枚举值可以隐式转换为与Enum基本类型匹配的整数值类型.在这种情况下为整数.数值0转换为False.由于DayOfWeek.Sunday的基础值为0,因此Not表达式始终生成True.

The Not operator in Visual Basic accepts a Boolean or numeric expression. Just like in C#, an enum value is implicitly convertable to an integral value type that matches the Enum's base type. Integer in this case. A numeric value of 0 converts to False. Since DayOfWeek.Sunday's underlying value is 0, the Not expression always produces True.

因此,这是可接受的语法.但是,您确实会收到此代码的警告,与在C#中得到的错误非常相似:

So this is acceptable syntax. You do however get a warning for this code, very similar to the error you get in C#:

警告BC42025:通过实例访问共享成员,常量成员,枚举成员或嵌套类型;合格的表达式将不会被评估.

warning BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.

由actdate.DayOfWeek属性表达式中使用的Sunday枚举成员产生.那肯定是代码的味道.除了不忽略警告之外,您还可以将该警告转变为错误.项目+属性,编译选项卡,警告配置部分.将实例变量访问共享的成员"设置从警告"更改为错误".

Produced by the Sunday enum member used in the actdate.DayOfWeek property expression. That is certainly a code smell. Short from not ignoring warnings, you can turn that warning into an error. Project + Properties, Compile tab, Warning configuration section. Change the "Instance variable accesses shared member" setting from Warning to Error.

这篇关于为什么还要编译这些代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆