DynamicObject.TryGetIndex(GetIndexBinder, Object[], Object) Méthode

Définition

Fournit l'implémentation pour les opérations qui obtiennent une valeur par index. Les classes dérivées de la classe DynamicObject peuvent substituer cette méthode afin de spécifier le comportement dynamique pour les opérations d'indexation.

public:
 virtual bool TryGetIndex(System::Dynamic::GetIndexBinder ^ binder, cli::array <System::Object ^> ^ indexes, [Runtime::InteropServices::Out] System::Object ^ % result);
public virtual bool TryGetIndex (System.Dynamic.GetIndexBinder binder, object[] indexes, out object result);
public virtual bool TryGetIndex (System.Dynamic.GetIndexBinder binder, object[] indexes, out object? result);
abstract member TryGetIndex : System.Dynamic.GetIndexBinder * obj[] * obj -> bool
override this.TryGetIndex : System.Dynamic.GetIndexBinder * obj[] * obj -> bool
Public Overridable Function TryGetIndex (binder As GetIndexBinder, indexes As Object(), ByRef result As Object) As Boolean

Paramètres

binder
GetIndexBinder

Fournit des informations sur l'opération.

indexes
Object[]

Index utilisés pendant l'opération. Par exemple, pour l’opération sampleObject[3] en C# (sampleObject(3) en Visual Basic), où sampleObject est dérivé de la DynamicObject classe, indexes[0] est égal à 3.

result
Object

Résultat de l'opération d'indexation.

Retours

true si l'opération réussit ; sinon false. Si cette méthode retourne false, le binder d'exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime est levée.)

Exemples

Supposons que vous souhaitiez créer un objet dans lequel les propriétés sont accessibles soit par des noms tels que Property0, Property1, et ainsi de suite, soit par index, de sorte que, par exemple, sampleObject.Property0 soit équivalent à sampleObject[0] en C# ou sampleObject(0) en Visual Basic.

L’exemple de code suivant illustre la SampleDynamicObject classe, qui est dérivée de la DynamicObject classe . La SampleDynamicObject classe contient un objet du Dictionary<string, object> type (Dictionary(Of String, Object) en Visual Basic) pour stocker les paires clé-valeur. SampleDynamicObjectremplace les méthodes et TryGetIndex pour activer l’accès TrySetIndex par index. Il remplace les méthodes et TryGetMember pour activer l’accès TrySetMember par nom de propriété.

// 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

Remarques

Les classes dérivées de la DynamicObject classe peuvent remplacer cette méthode pour spécifier la façon dont l’obtention d’une valeur par index doit être effectuée pour un objet dynamique. Lorsque la méthode n’est pas remplacée, le classeur d’exécution du langage détermine le comportement. (Dans la plupart des cas, une exception runtime est levée.)

Si cette méthode est remplacée, elle est appelée automatiquement lorsque vous avez une opération comme sampleObject[3] en C# ou sampleObject(3) en Visual Basic, où sampleObject est dérivée de la DynamicObject classe .

S’applique à