Partilhar via


SqlConnectionStringBuilder.TryGetValue(String, Object) Método

Definição

Recupera um valor correspondente para a chave fornecida deste SqlConnectionStringBuilder.

public:
 override bool TryGetValue(System::String ^ keyword, [Runtime::InteropServices::Out] System::Object ^ % value);
public override bool TryGetValue (string keyword, out object value);
override this.TryGetValue : string * obj -> bool
Public Overrides Function TryGetValue (keyword As String, ByRef value As Object) As Boolean

Parâmetros

keyword
String

A chave do item a ser recuperada.

value
Object

O valor correspondente a keyword.

Retornos

true se keyword tiver sido encontrado na cadeia de conexão, caso contrário, false.

Exceções

keyword contém um valor nulo (Nothing no Visual Basic).

Exemplos

O exemplo a seguir demonstra o comportamento do método TryGetValue .

using System.Data.SqlClient;

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder.ConnectionString = GetConnectionString();

        // Call TryGetValue method for multiple
        // key names. Note that these keys are converted
        // to well-known synonynms for data retrieval.
        DisplayValue(builder, "Data Source");
        DisplayValue(builder, "Trusted_Connection");
        DisplayValue(builder, "InvalidKey");
        DisplayValue(builder, null);

        Console.WriteLine("Press any key to continue.");
        Console.ReadLine();
    }

    private static void DisplayValue(
        SqlConnectionStringBuilder builder, string key)
    {
        object value = null;

        // Although TryGetValue handles missing keys,
        // it doesn't handle passing in a null
        // key. This example traps for that particular error, but
        // passes any other unknown exceptions back out to the
        // caller.
        try
        {
            if (builder.TryGetValue(key, out value))
            {
                Console.WriteLine("{0}='{1}'", key, value);
            }
            else
            {
                Console.WriteLine("Unable to retrieve value for '{0}'", key);
            }
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("Unable to retrieve value for null key.");
        }
    }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,
        // you can retrieve it from a configuration file.
        return "Server=(local);Integrated Security=SSPI;" +
            "Initial Catalog=AdventureWorks";
    }
}
Imports System.Data.SqlClient
    
Module Module1
    Sub Main()
        Dim builder As New SqlConnectionStringBuilder
        builder.ConnectionString = GetConnectionString()

        ' Call TryGetValue method for multiple
        ' key names. Note that these keys are converted
        ' to well-known synonynms for data retrieval.
        DisplayValue(builder, "Data Source")
        DisplayValue(builder, "Trusted_Connection")
        DisplayValue(builder, "InvalidKey")
        DisplayValue(builder, Nothing)

        Console.WriteLine("Press any key to continue.")
        Console.ReadLine()
    End Sub

    Private Sub DisplayValue( _
     ByVal builder As SqlConnectionStringBuilder, ByVal key As String)
        Dim value As Object = Nothing

        ' Although TryGetValue handles missing keys,
        ' it doesn't handle passing in a null (Nothing in Visual Basic)
        ' key. This example traps for that particular error, but
        ' passes any other unknown exceptions back out to the
        ' caller. 
        Try
            If builder.TryGetValue(key, value) Then
                Console.WriteLine("{0}='{1}' ", key, value)
            Else
                Console.WriteLine("Unable to retrieve value for '{0}'", key)
            End If
        Catch ex As ArgumentNullException
            Console.WriteLine("Unable to retrieve value for null key.")
        End Try
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the connection string in your code,
        ' you can retrieve it from a configuration file. 
        Return "Server=(local);Integrated Security=SSPI;" & _
          "Initial Catalog=AdventureWorks"
    End Function
End Module

O exemplo exibe os seguintes resultados:

Data Source=(local)
Trusted_Connection=True
Unable to retrieve value for 'InvalidKey'
Unable to retrieve value for null key.

Comentários

O TryGetValue método permite que os desenvolvedores recuperem com segurança um valor de um SqlConnectionStringBuilder sem a necessidade de verificar se o nome da chave fornecida é um nome de chave válido. Como TryGetValue não gera uma exceção quando você a chama, passando uma chave inexistente, você não precisa procurar uma chave antes de recuperar seu valor. Chamar TryGetValue com uma chave inexistente colocará o valor nulo (Nothing no Visual Basic) no value parâmetro .

Aplica-se a

Confira também