AppContext.TryGetSwitch(String, Boolean) Método

Definição

Tenta obter o valor de um interruptor.

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 do switch.

isEnabled
Boolean

Quando este método retorna, contém o valor de switchName se switchName foi encontrado, ou false se switchName não foi encontrado. Este parâmetro é passado sem inicializar.

Devoluções

true se switchName foi definido e o isEnabled argumento contém o valor do interruptor; caso contrário, false.

Exceções

switchName é null.

switchName é Empty.

Exemplos

O exemplo seguinte determina se um consumidor de biblioteca definiu um switch chamado 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

Observações

A classe AppContext permite que os escritores de bibliotecas forneçam um mecanismo de exclusão uniforme para novas funcionalidades para seus usuários. Estabelece um contrato de acoplamento frouxo entre componentes, a fim de comunicar um pedido de autoexclusão. Esse recurso geralmente é importante quando uma alteração é feita na funcionalidade existente. Por outro lado, já existe um opt-in implícito para novas funcionalidades.

O tempo de execução da linguagem comum preenche automaticamente os interruptores atribuídos a uma AppContext instância, lendo o registo e o ficheiro de configuração da aplicação. O valor destes interruptores pode então ser sobreposto e novos interruptores adicionados, chamando o SetSwitch método.

Uma biblioteca chama o TryGetSwitch método para verificar se os seus consumidores declararam o valor do switch e depois agir adequadamente sobre ele. Por defeito, se o interruptor não estiver definido, a nova funcionalidade fica ativada. Se o switch estiver definido e o seu valor for false, a nova funcionalidade também é ativada. Se o seu valor for true, o comportamento legado está ativado.

Aplica-se a

Ver também