DynamicObject.TrySetIndex(SetIndexBinder, Object[], Object) Método

Definição

Fornece a implementação para operações que definem um valor por índice. As classes derivadas da classe DynamicObject podem substituir este método para especificar o comportamento dinâmico para operações que acessam os objetos por um índice especificado.

public:
 virtual bool TrySetIndex(System::Dynamic::SetIndexBinder ^ binder, cli::array <System::Object ^> ^ indexes, System::Object ^ value);
public virtual bool TrySetIndex (System.Dynamic.SetIndexBinder binder, object[] indexes, object value);
public virtual bool TrySetIndex (System.Dynamic.SetIndexBinder binder, object[] indexes, object? value);
abstract member TrySetIndex : System.Dynamic.SetIndexBinder * obj[] * obj -> bool
override this.TrySetIndex : System.Dynamic.SetIndexBinder * obj[] * obj -> bool
Public Overridable Function TrySetIndex (binder As SetIndexBinder, indexes As Object(), value As Object) As Boolean

Parâmetros

binder
SetIndexBinder

Fornece informações sobre a operação.

indexes
Object[]

Os índices usados na operação. Por exemplo, para a operação sampleObject[3] = 10 no C# (sampleObject(3) = 10 no Visual Basic), em que sampleObject é derivado da classe DynamicObject, indexes[0] é igual a 3.

value
Object

O valor a ser definido para o objeto que tem o índice especificado. Por exemplo, para a sampleObject[3] = 10 operação em C# (sampleObject(3) = 10 no Visual Basic), em que sampleObject é derivada da DynamicObject classe , value é igual a 10.

Retornos

true se a operação for bem-sucedida; caso contrário, false. Se esse método retornar false, o associador de tempo de execução da linguagem determinará o comportamento. (Na maioria dos casos, uma exceção de tempo de execução específica a um idioma é gerada.

Exemplos

Suponha que você queira criar um objeto no qual as propriedades possam ser acessadas por nomes como Property0, Property1e assim por diante ou por índice, de modo que, por exemplo, sampleObject.Property0 seja equivalente a sampleObject[0] em C# ou sampleObject(0) no Visual Basic.

O exemplo de código a seguir demonstra a SampleDynamicObject classe , que é derivada da DynamicObject classe . A SampleDynamicObject classe contém um objeto do Dictionary<string, object> tipo (Dictionary(Of String, Object) no Visual Basic) para armazenar os pares chave-valor. SampleDynamicObjectsubstitui os métodos e TryGetIndex para habilitar o TrySetIndex acesso por índice. Ele substitui os métodos e TryGetMember para habilitar o TrySetMember acesso pelo nome da propriedade.

// The class derived from DynamicObject.
public class SampleDynamicObject : DynamicObject
{
    // The inner dictionary to store field names and values.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // Get the property value.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    // Set the property value.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }

    // Set the property value by index.
    public override bool TrySetIndex(
        SetIndexBinder binder, object[] indexes, object value)
    {
        int index = (int)indexes[0];

        // If a corresponding property already exists, set the value.
        if (dictionary.ContainsKey("Property" + index))
            dictionary["Property" + index] = value;
        else
            // If a corresponding property does not exist, create it.
            dictionary.Add("Property" + index, value);
        return true;
    }

    // Get the property value by index.
    public override bool TryGetIndex(
        GetIndexBinder binder, object[] indexes, out object result)
    {

        int index = (int)indexes[0];
        return dictionary.TryGetValue("Property" + index, out result);
    }
}

class Program
{
    static void Test(string[] args)
    {
        // Creating a dynamic object.
        dynamic sampleObject = new SampleDynamicObject();

        // Creating Property0.
        // The TrySetMember method is called.
        sampleObject.Property0 = "Zero";

        // Getting the value by index.
        // The TryGetIndex method is called.
        Console.WriteLine(sampleObject[0]);

        // Setting the property value by index.
        // The TrySetIndex method is called.
        // (This method also creates Property1.)
        sampleObject[1] = 1;

        // Getting the Property1 value.
        // The TryGetMember method is called.
        Console.WriteLine(sampleObject.Property1);

        // The following statement produces a run-time exception
        // because there is no corresponding property.
        //Console.WriteLine(sampleObject[2]);
    }
}

// This code example produces the following output:

// Zero
// 1
' The class derived from DynamicObject.
Public Class SampleDynamicObject
    Inherits DynamicObject

    ' The inner dictionary to store field names and values.
    Dim dictionary As New Dictionary(Of String, Object)

    ' Get the property value.
    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder,
        ByRef result As Object) As Boolean

        Return dictionary.TryGetValue(binder.Name, result)

    End Function

    ' Set the property value.
    Public Overrides Function TrySetMember(
        ByVal binder As System.Dynamic.SetMemberBinder,
        ByVal value As Object) As Boolean

        dictionary(binder.Name) = value
        Return True

    End Function

    ' Set the property value by index.
    Public Overrides Function TrySetIndex(
        ByVal binder As System.Dynamic.SetIndexBinder,
        ByVal indexes() As Object, ByVal value As Object) As Boolean

        Dim index As Integer = CInt(indexes(0))
        ' If a corresponding property already exists, set the value.
        If (dictionary.ContainsKey("Property" & index)) Then
            dictionary("Property" & index) = value
        Else
            ' If a property does not exist, create it.
            dictionary.Add("Property" & index, value)
        End If
        Return True
    End Function

    ' Get the property value by index.
    Public Overrides Function TryGetIndex(
        ByVal binder As System.Dynamic.GetIndexBinder,
        ByVal indexes() As Object, ByRef result As Object) As Boolean

        Dim index = CInt(indexes(0))
        Return dictionary.TryGetValue("Property" & index, result)
    End Function
End Class

Sub Test()
    ' Creating a dynamic object.
    Dim sampleObject As Object = New SampleDynamicObject()

    ' Creating Property0.
    ' The TrySetMember method is called.
    sampleObject.Property0 = "Zero"

    ' Getting the value by index.
    ' The TryGetIndex method is called.
    Console.WriteLine(sampleObject(0))

    ' Setting the property value by index.
    ' The TrySetIndex method is called.
    ' (This method also creates Property1.)
    sampleObject(1) = 1

    ' Getting the Property1 value.
    ' The TryGetMember method is called.
    Console.WriteLine(sampleObject.Property1)

    ' The following statement produces a run-time exception
    ' because there is no corresponding property.
    ' Console.WriteLine(sampleObject(2))
End Sub

' This code example produces the following output:

' Zero
' 1

Comentários

Classes derivadas da DynamicObject classe podem substituir esse método para especificar como as operações que acessam um objeto por índice devem ser executadas para um objeto dinâmico. Quando o método não é substituído, o associador de tempo de execução do idioma determina o comportamento. (Na maioria dos casos, uma exceção de tempo de execução específica a um idioma é gerada.)

Se esse método for substituído, ele será invocado automaticamente quando você tiver uma operação como sampleObject[3] = 10 em C# ou sampleObject(3) = 10 no Visual Basic, em sampleObject que é derivado da DynamicObject classe .

Aplica-se a