对象初始化器
-
命名类型
Dim someInstance As New SomeClass(argument) With { .Member1 = value1, .Member2 = value2 '... }
相当于
Dim someInstance As New SomeClass(argument) someInstance.Member1 = value1 someInstance.Member2 = value2 '...
-
匿名类型 (选项推断必须打开)
Dim anonymousInstance = New With { .Member1 = value1, .Member2 = value2 '... }
虽然类似的
anonymousInstance
与someInstance
的类型不同成员名称在匿名类型中必须是唯一的,并且可以从变量或其他对象成员名称中获取
Dim anonymousInstance = New With { value1, value2, foo.value3 '... } ' usage : anonymousInstance.value1 or anonymousInstance.value3
每个成员都可以以
Key
关键字开头。那些成员将是ReadOnly
属性,那些没有将是读/写属性Dim anonymousInstance = New With { Key value1, .Member2 = value2, Key .Member3 = value3 '... }
使用相同成员定义的两个匿名实例(名称,类型,
Key
和 order 的存在)将具有相同的匿名类型。Dim anon1 = New With { Key .Value = 10 } Dim anon2 = New With { Key .Value = 20 } anon1.GetType Is anon2.GetType ' True
匿名类型在结构上是等同的。具有至少一个具有相同
Key
值的Key
属性的相同匿名类型的两个实例将是相等的。你必须使用Equals
方法来测试它,使用=
将无法编译,Is
将比较对象引用。Dim anon1 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 0 } Dim anon2 = New With { Key .Name = "Bar", Key .Age = 20, .Salary = 0 } Dim anon3 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 10000 } anon1.Equals(anon2) ' False anon1.Equals(anon3) ' True although non-Key Salary isn't the same
Named 和 Anonymous 类型的初始值设定项都可以嵌套和混合
Dim anonymousInstance = New With {
value,
Key .someInstance = New SomeClass(argument) With {
.Member1 = value1,
.Member2 = value2
'...
}
'...
}