Visual Basic中如何在类内声明固定长度的数组属性?
问题解决:声明固定长度并初始化全0的Public Property数组
错误原因解析
你遇到的错误翻译为:
错误BC36759:自动实现的属性不能包含参数
原代码的问题在于:
- 自动实现属性(
Public Property ... As ...这种简写形式)不允许带参数; - 数组的声明语法不符合VB规范,不能直接在属性名后用
(width*height)指定长度。
解决方案
根据width和height是否为固定值,提供两种实现方式:
1. 当width和height是固定常量时
Public Class Board ' 定义固定的宽高常量 Private Const BoardWidth As Integer = 2 Private Const BoardHeight As Integer = 4 ' 私有字段:初始化数组为指定长度,所有元素默认值为0 Private _squares As Integer() = New Integer(BoardWidth * BoardHeight - 1) {} ' 公开属性 Public Property squares() As Integer() Get Return _squares End Get Set(value As Integer()) ' 可选:校验赋值的数组长度是否符合要求 If value.Length <> BoardWidth * BoardHeight Then Throw New ArgumentException($"数组长度必须为{BoardWidth * BoardHeight}") End If _squares = value End Set End Property End Class
2. 当width和height需要实例化时传入
Public Class Board Private ReadOnly _width As Integer Private ReadOnly _height As Integer Private _squares As Integer() ' 构造函数:传入宽高并初始化数组 Public Sub New(boardWidth As Integer, boardHeight As Integer) _width = boardWidth _height = boardHeight ' 初始化数组,所有元素默认值为0 _squares = New Integer(boardWidth * boardHeight - 1) {} End Sub Public Property squares() As Integer() Get Return _squares End Get Set(value As Integer()) If value.Length <> _width * _height Then Throw New ArgumentException($"数组长度必须为{_width * _height}") End If _squares = value End Set End Property End Class
3. 只读属性(仅允许修改数组元素,不允许替换整个数组)
如果不需要外部替换整个数组,仅允许修改单个元素,可以将属性设为只读:
Public Class Board Private Const BoardWidth As Integer = 2 Private Const BoardHeight As Integer = 4 ' 只读私有字段,初始化后无法替换数组引用 Private ReadOnly _squares As Integer() = New Integer(BoardWidth * BoardHeight - 1) {} Public ReadOnly Property squares() As Integer() Get Return _squares End Get End Property End Class
说明:VB中声明
New Integer(n){}时,数组的索引范围是0到n,总元素个数为n+1。因此要创建长度为width*height的数组,需使用New Integer(width*height -1){},且值类型Integer的默认值为0,无需额外赋值。
内容的提问来源于stack exchange,提问作者pfzhou
相关产品推荐
相关产品推荐

