同一类中的重复属性和局部变量名

时间:2017-05-12 07:22:15

标签: vb.net visual-studio-2013

我很困惑地发现VB.NET允许我在一个与类中属性同名的方法中声明一个局部变量。我发现了错误,因为程序没有像我预期的那样工作,但编译器甚至没有警告我这个可能的冲突。我的意思的一个简单例子:

Public Class Form1
    Property Foo As Decimal

    Public Sub New()
        InitializeComponent()
        Foo = 1
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Foo As Integer 'This variable hides the property with the same name

        If Foo > 0 Then 'The local variable value will be used here and the if statement won't be evaluated to true
            'Do Something
        End If
    End Sub
End Class

有关如何通过编译器警告或最佳做法处理此类情况的任何建议以避免这种情况?从C#转到VB,我甚至没想到会发生这样的事情。这甚至不是我写的程序,我不得不在工作中修改其他人的代码。

一个解决方案是使用 Me 前缀明确引用该属性:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Foo As Integer 'This variable hides the property with the same name

    If Me.Foo > 0 Then 'The property value will be used here and the if statement WILL be evaluated to true
        'Do Something
    End If
End Sub

您应该习惯于始终引用属性以避免此类问题。有没有更好的解决方案?

0 个答案:

没有答案