物件初始化器

  • 命名型別

     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
          '...
      }
    

    雖然類似的 anonymousInstancesomeInstance 的型別不同

    成員名稱在匿名型別中必須是唯一的,並且可以從變數或其他物件成員名稱中獲取

      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
            '...
        }
        '...
    }