VB.NET 中的隐式转换
这个问题是针对懒惰的 VB 程序员的。请。
在 vb 中我可以做到并且不会出现任何错误。
示例 1
Dim x As String = 5
Dim y As Integer = "5"
Dim b As Boolean = "True"
示例 2
Dim a As EnumType = 4
Dim v As Integer = EnumType.EnumValue
示例 3
Private Sub ButtonClick(sender As Object, e As EventArgs)
Dim btn As Button = sender
End Sub
示例 4
Private Sub ButtonClick(sender As Button, e As EventArgs)
Dim data As Contact = sender.Tag
End Sub
如果我确实知道预期的运行时类型,那么这是否“禁止”依赖 vb 语言的内置转换? 什么时候我才可以依靠呢?
The question is intended for lazy VB programmers. Please.
In vb I can do and I won't get any errors.
Example 1
Dim x As String = 5
Dim y As Integer = "5"
Dim b As Boolean = "True"
Example 2
Dim a As EnumType = 4
Dim v As Integer = EnumType.EnumValue
Example 3
Private Sub ButtonClick(sender As Object, e As EventArgs)
Dim btn As Button = sender
End Sub
Example 4
Private Sub ButtonClick(sender As Button, e As EventArgs)
Dim data As Contact = sender.Tag
End Sub
If I surely know the expected runtime type, is this 'forbidden' to rely on the vb-language built-in casting?
When can I rely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然并不是“禁止”使用
Option Strict Off
,但几乎每个人都强烈建议使用Option Strict On
。其他问题中解释了原因,例如这个。
It is certainly not "forbidden" to use
Option Strict Off
but nearly everyone strongly advises usingOption Strict On
.The reasons are explained in other questions, for instance this.
对 MarkJ 的评论移动以回答每个 OP
您可以随意依赖它,只要确保您知道隐式转换正在执行的操作的规则即可。也就是说,示例 #4 看起来将来很容易被破坏,如果之前至少有一个空检查,我会更高兴。
Comment to MarkJ move to answer per OP
Feel free to rely on it all you want, just make sure you know the rules for what the implicit cast is doing. That said, example #4 looks really easy to break in the future, I'd be much happier if there was at least a null-check before.
如果您使用的是 Visual Basic 2008,另一个选项是显式进行转换(例如 Option Strict On)并依赖 Option Implicit On,这样您就不需要两次编写类型。
If you are using Visual Basic 2008, another option is doing the casting explicitaly (e.g. Option Strict On) and rely on the Option Implicit On so you don't need to write the type twice.
具有讽刺意味的是,像这样的“懒惰”做法从长远来看往往会花费你更多的时间。您真的可以绝对确定您的输入将始终采用可以在所有情况下和所有区域设置下自动转换为预期类型的格式吗?
考虑所有可能的影响并处理几乎不可避免的错误,可能会花费更多的时间,而不仅仅是强类型变量、严格验证输入以及在需要时显式转换。
The irony of "lazy" practices like this is that they often end up costing you more time in the long run. Can you really be absolutely certain that your inputs will always be in a format that can automatically be cast to the intended type, under all circumstances and in all locales?
Thinking through all the possible implications, and handling the almost inevitable bugs, will probably take more time than just strongly typing your variables, strictly validating your inputs, and explicitly casting where needed.