VB.NET中只读集合属性的集合初始值设定项?

Ant*_*ada 5 .net vb.net collections syntax properties

我正在尝试在我的框架上支持Basic.NET,所以我试图将C#4代码转换为Basic.NET 10.微软致力于"共同演化"这两个,但我遇到了集合初始化的问题. ..

我发现我可以像C#一样初始化一个集合:

Dim list = New List(Of Int32) From {1, 2, 3, 4, 5, 6, 7, 8, 9}
Run Code Online (Sandbox Code Playgroud)

大!但是,在初始化只读集合属性时,这不起作用.例如,如果我有这个类:

Public Class Class1

  Private ReadOnly list = New List(Of Int32)

  Public ReadOnly Property ListProp() As List(Of Int32)
    Get
      Return list
    End Get
  End Property

End Class
Run Code Online (Sandbox Code Playgroud)

我无法以这种方式初始化它:

Dim class1 = New Class1 With {.ListProp = New List(Of Int32) From {1, 2, 3, 4, 5, 6, 7, 8, 9}}
Run Code Online (Sandbox Code Playgroud)

或者这样:

Dim class1 = New Class1 With {.ListProp = {1, 2, 3, 4, 5, 6, 7, 8, 9}}
Run Code Online (Sandbox Code Playgroud)

我得到一个"Property'ListProp'是'ReadOnly'." 消息,这是正确的,但在这里说,在Basic.NET中支持集合初始化程序,其中自动调用Add方法.我错过了什么或不支持属性吗?C#4支持这个......

在此先感谢,aalmada

编辑:

以下是等效的可编译C#代码供参考:

using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    class Class1
    {
        private readonly List<Int32> list = new List<Int32>();

        public List<Int32> ListProp
        {
            get
            {
                return this.list;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // a collection initialization
            var list = new List<Int32> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            // a read-only collection property initialization
            var class1 = new Class1
            {
                ListProp = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 1

您正在尝试将该ListProp属性设置为新List(Of Int32)实例。

既然是ReadOnly,你就不能这么做。