来自Getter的VB.NET呼叫设置器 [英] VB.NET Call Setter from within Getter

查看:66
本文介绍了来自Getter的VB.NET呼叫设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的班级:

Public Class MyClass

Private _intList As New List(Of Integer)
Private _avg As Decimal

Public Sub Add(ByVal anInt As Integer)
    _intList.Add(anInt)
End Sub

Public Property Avg() As Decimal
    Get
        Dim _sum As Integer = 0
        For Each anInt In _intList
            _sum += anInt
        Next
        Avg = If((_intList.Count > 0), _sum / _intList.Count, _avg)
        Return _avg
    End Get
    Set(ByVal value As Decimal)
        If _avg <> value Then
            _avg = value
            Console.WriteLine("Value changed")
        End If
    End Set
End Property

End Class

Getter正在计算平均值,然后调用Setter保存该值.由于某种原因,我无法理解,平均值始终为0.例如:

The Getter is calculating average and calls Setter to save the value. For some reason I cannot understand, the average is always 0. For example:

Dim c As New Class2()
c.Add(1)
c.Add(2)
c.Add(3)
Console.WriteLine(c.Avg.ToString()) ' This will print 0

我做错了吗?是什么原因造成的?

Did I do something wrong? What is the cause of this?

推荐答案

这是设计使然,并在Visual Basic语言规范的第9.7.1章中明确提及:

This is by design and explicitly mentioned in the Visual Basic Language Specification, chapter 9.7.1:

特殊的局部变量,在Get中隐式声明 与属性同名的访问者主体的声明空间, 表示属性的返回值.局部变量有 在表达式中使用特殊的名称解析语义.如果 局部变量用于需要以下表达式的上下文中 归类为方法组(例如调用表达式),然后 名称解析为函数而不是局部变量. 例如:

A special local variable, which is implicitly declared in the Get accessor body's declaration space with the same name as the property, represents the return value of the property. The local variable has special name resolution semantics when used in expressions. If the local variable is used in a context that expects an expression that is classified as a method group, such as an invocation expression, then the name resolves to the function rather than to the local variable. For example:

ReadOnly Property F(i As Integer) As Integer
    Get
        If i = 0 Then
            F = 1    ' Sets the return value.
        Else
            F = F(i - 1) ' Recursive call.
        End If
    End Get
End Property

直接分配_avg字段即可解决您的问题.最好避免具有这种副作用的吸气剂.

Solve your issue by assigning the _avg field directly. Property getters with side-effects like this is best avoided.

这篇关于来自Getter的VB.NET呼叫设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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