AppContext.TryGetSwitch(String, Boolean) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
試圖取得開關的價值。
public:
static bool TryGetSwitch(System::String ^ switchName, [Runtime::InteropServices::Out] bool % isEnabled);
public static bool TryGetSwitch(string switchName, out bool isEnabled);
static member TryGetSwitch : string * bool -> bool
Public Shared Function TryGetSwitch (switchName As String, ByRef isEnabled As Boolean) As Boolean
參數
- switchName
- String
那個開關的名字。
- isEnabled
- Boolean
當此方法回傳時,包含 如果找到了,switchNameswitchName或如果找不到,則 包含了 的falseswitchName值。 這個參數會未初始化傳遞。
傳回
true 若 switchName 被設定 isEnabled 且參數包含交換器值;否則, false。
例外狀況
switchName 是 null。
switchName 是 Empty。
範例
以下範例判斷函式庫使用者是否設定了一個名為 Switch.AmazingLib.ThrowOnException的交換器。
public class AmazingLib
{
private bool shouldThrow;
public void PerformAnOperation()
{
if (!AppContext.TryGetSwitch("Switch.AmazingLib.ThrowOnException", out shouldThrow)) {
// This is the case where the switch value was not set by the application.
// The library can choose to get the value of shouldThrow by other means.
// If no overrides or default values are specified, the value should be 'false'.
// A false value implies the latest behavior.
}
// The library can use the value of shouldThrow to throw exceptions or not.
if (shouldThrow) {
// old code
}
else {
// new code
}
}
}
module AmazingLib =
let performAnOperation () =
match AppContext.TryGetSwitch "Switch.AmazingLib.ThrowOnException" with
| false, _ ->
// This is the case where the switch value was not set by the application.
// The library can choose to get the value of shouldThrow by other means.
// If no overrides or default values are specified, the value should be 'false'.
// A false value implies the latest behavior.
()
| true, shouldThrow ->
// The library can use the value of shouldThrow to throw exceptions or not.
if shouldThrow then
// old code
()
else
// new code
()
Public Class AmazingLib
Private shouldThrow As Boolean
Public Sub PerformAnOperation()
If Not AppContext.TryGetSwitch("Switch.AmazingLib.ThrowOnException", shouldThrow) Then
' This is the case where the switch value was not set by the application.
' The library can choose to get the value of shouldThrow by other means.
' If no overrides or default values are specified, the value should be 'false'.
' A false value implies the latest behavior.
End If
' The library can use the value of shouldThrow to throw exceptions or not.
If shouldThrow Then
' old code
Else
' new code
End If
End Sub
End Class
備註
AppContext 類別可讓程式庫開發者為其使用者提供統一的退出機制。 它會建立元件之間的鬆散結合合約,以傳達退出要求。 當對現有功能進行變更時,這項功能通常很重要。 相反地,對於新功能來說,已經有隱含的默認同意。
通用語言執行時會自動讀取登錄檔和應用程式的設定檔,來填入分配給實 AppContext 例的交換器。 這些交換器的值可以被覆蓋,並新增交換器,方法是呼叫該 SetSwitch 方法。
函式庫呼叫該 TryGetSwitch 方法以檢查其使用者是否宣告了交換器的值,然後對此適當行動。 預設情況下,如果交換器未定義,新功能會被啟用。 若交換器定義且其值為 false,則新功能也會被啟用。 若其值為 true,則啟用舊有行為。