AppContext.TryGetSwitch(String, Boolean) Método
Definição
Tenta obter o valor de um comutador.Tries to get the value of a switch.
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
Parâmetros
- switchName
- String
O nome de opção.The name of the switch.
- isEnabled
- Boolean
Quando esse método for retornado, conterá o valor de switchName se switchName tiver sido encontrada ou false se switchName não tiver sido.When this method returns, contains the value of switchName if switchName was found, or false if switchName was not found. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
Retornos
true se switchName estiver definido e o argumento isEnabled contiver o valor do comutador; caso contrário, false.true if switchName was set and the isEnabled argument contains the value of the switch; otherwise, false.
Exceções
switchName é null.switchName is null.
Exemplos
O exemplo a seguir determina se um consumidor de biblioteca definiu uma opção chamada Switch.AmazingLib.ThrowOnException .The following example determines whether a library consumer has set a switch named 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
}
}
}
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
Comentários
A AppContext classe permite que os gravadores de biblioteca forneçam um mecanismo de aceitação uniforme para novas funcionalidades para seus usuários.The AppContext class enables library writers to provide a uniform opt-out mechanism for new functionality for their users. Ele estabelece um contrato livremente acoplado entre componentes para comunicar uma solicitação de recusa.It establishes a loosely coupled contract between components in order to communicate an opt-out request. Normalmente, essa funcionalidade é importante quando uma alteração é feita na funcionalidade existente.This capability is typically important when a change is made to existing functionality. Por outro lado, já existe uma aceitação implícita da nova funcionalidade.Conversely, there is already an implicit opt-in for new functionality.
O Common Language Runtime preenche automaticamente as opções atribuídas a uma AppContext instância lendo o registro e o arquivo de configuração do aplicativo.The common language runtime automatically populates the switches assigned to an AppContext instance by reading the registry and the application's configuration file. O valor dessas opções pode ser substituído e novas opções adicionadas, chamando o SetSwitch método.The value of these switches can then be overridden, and new switches added, by calling the SetSwitch method.
Uma biblioteca chama o TryGetSwitch método para verificar se seus consumidores declararam o valor da opção e, em seguida, atuam adequadamente nele.A library calls the TryGetSwitch method to check whether its consumers have declared the value of the switch and then act appropriately on it. Por padrão, se a opção não estiver definida, a nova funcionalidade será habilitada.By default, if the switch is not defined, the new functionality is enabled. Se a opção for definida e seu valor for false , a nova funcionalidade também será habilitada.If the switch is defined and its value is false, the new functionality is also enabled. Se seu valor for true , o comportamento herdado será habilitado.If its value is true, the legacy behavior is enabled.