gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:54:02 25 4
gpt4 key购买 nike

我正在尝试在我的框架上支持 Basic.NET,所以我正在尝试将 C# 4 代码转换为 Basic.NET 10。Microsoft 致力于“共同进化”这两个代码,但我在集合初始化方面遇到了问题。 ..

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

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

伟大的!
但这在初始化只读集合属性时不起作用。例如,如果我有这个类:
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

我无法以这种方式初始化它:
Dim class1 = New Class1 With {.ListProp = New List(Of Int32) From {1, 2, 3, 4, 5, 6, 7, 8, 9}}

或者这样:
Dim class1 = New Class1 With {.ListProp = {1, 2, 3, 4, 5, 6, 7, 8, 9}}

我得到一个“属性 'ListProp' 是 'ReadOnly'。”消息是正确的,但它说 here Basic.NET 支持该集合初始值设定项,其中自动调用 Add 方法。我是否遗漏了某些东西,或者这不支持属性吗? C# 4 支持这个...

提前致谢,
阿尔马达

编辑:

这是等效的可编译 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 }
};
}
}
}

最佳答案

您正在尝试设置 ListProp新的属性(property)List(Of Int32)实例。

既然是 ReadOnly ,你不能那样做。

关于.net - VB.NET 中只读集合属性的集合初始值设定项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com