【问题标题】:Prevent StackOverflowException in Property-Definition in .Net在 .Net 中的属性定义中防止 StackOverflowException
【发布时间】:2015-11-17 09:26:13
【问题描述】:

在我的班级中,“子进程”负责在属性(列表(整数))中产生一些值。这个子进程应该总是在获取到属性值的时候调用。

MustInherit Class TestClassBase
   Private _OutputList As New List(Of Integer)

   Public Property OutputList() As List(Of Integer)
       Get
           Me.Process()
           Return _OutputList
       End Get
       Set(ByVal value As List(Of Integer))
           _OutputList = value
       End Set
   End Property

   Public MustOverride Sub Process()
End Class


Class TestClass
   Inherits TestClassBase

   Public Overrides Sub Process()
       OutputList.Clear()
       OutputList.Add(1)
       OutputList.Add(2)
       OutputList.Add(3)
   End Sub
End Class


Module ModuleTest
   Sub Main()
       Dim tmpList As New TestClass
       tmpList.Process()
   End Sub
End Module

在属性的 Get-Part 中调用 Me.Process 会产生 StackOverflowException。由于 TestclassBase 作为 Mustinherit 并且需要在继承的类中实现“子流程”,我无权访问 Private _Outputlist。

解决这个问题最优雅的方法是什么?

【问题讨论】:

  • 将 _OutputList 访问修饰符从 Private 更改为 Protected。顺便说一句,让属性 getter 修改字段是一个非常糟糕的主意,属性 getter 永远不应该改变对象的状态。否则你遇到麻烦的根本原因。

标签: .net vb.net oop stack-overflow


【解决方案1】:

当您在调用OutputList getter 的Process 中调用OutputList.Clear() 时。然后该 getter 再次调用 Process,然后再次调用 OutputList.Clear()

此调用序列将继续进行,直到您用完堆栈并生成异常。

您需要停下来思考一下您在这里实际想要实现的目标(提示,在 getter 中进行处理通常是一个坏主意)并重新考虑您的设计。

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多