分享方式:


Bicep safe-dereference 運算子

safe-dereference 運算子提供了一種以安全的方式存取物件屬性或陣列元素的方法。 它有助於在嘗試存取不曉得其存在或值的屬性或元素時,防止可能的錯誤發生。

safe-dereference

<base>.?<property> <base>[?<index>]

在其運算元評估為非 Null 時,safe-dereference 運算子才會允許對其運算元進行成員存取 (.?<property>) 或陣列元素存取 ([?<index>]);若非如此,會傳回 null。 也就是說,

  • 如果 a 評估為 null,則 a.?xa[?x] 的結果為 null
  • 如果 a 是沒有 x 屬性的物件,則 a.?xnull
  • 如果 a 是長度小於或等於 x 的陣列,則 a[?x]null
  • 如果 a 為非 null 且具有名為 x 的屬性,則 a.?x 的結果與 a.x 的結果相同。
  • 如果 a 為非 null 且索引 x 具有元素,則 a[?x] 的結果與 a[x] 的結果相同

safe-dereference 運算子為最少運算。 換句話說,如果條件式成員或項目存取作業鏈結中的一個作業傳回 null,則鏈結的其餘部分不會執行。 在下列範例中,如果 storageAccountsettings[?i] 評估為 null,則不會評估 .?name

param storageAccountSettings array = []
param storageCount int
param location string = resourceGroup().location

resource storage 'Microsoft.Storage/storageAccounts@2023-04-01' = [for i in range(0, storageCount): {
  name: storageAccountSettings[?i].?name ?? 'defaultname'
  location: storageAccountSettings[?i].?location ?? location
  kind: storageAccountSettings[?i].?kind ?? 'StorageV2'
  sku: {
    name: storageAccountSettings[?i].?sku ?? 'Standard_GRS'
  }
}]

下一步