DynamicObject.TryGetMember(GetMemberBinder, Object) Metoda

Definicja

Zapewnia implementację operacji, które pobierają wartości składowe. Klasy pochodzące z DynamicObject klasy mogą zastąpić tę metodę w celu określenia dynamicznego zachowania operacji, takich jak pobieranie wartości dla właściwości.

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

Parametry

binder
GetMemberBinder

Zawiera informacje o obiekcie, który nazwał operację dynamiczną. Właściwość binder.Name zawiera nazwę elementu członkowskiego, na którym jest wykonywana operacja dynamiczna. Na przykład dla instrukcji Console.WriteLine(sampleObject.SampleProperty) , gdzie sampleObject jest wystąpieniem klasy pochodnej DynamicObject z klasy, binder.Name zwraca wartość "SampleProperty". Właściwość binder.IgnoreCase określa, czy nazwa elementu członkowskiego jest rozróżniana wielkość liter.

result
Object

Wynik operacji pobierania. Jeśli na przykład metoda jest wywoływana dla właściwości, można przypisać wartość właściwości do result.

Zwraca

true jeśli operacja zakończy się pomyślnie; w przeciwnym razie , false. Jeśli ta metoda zwróci falsewartość , powiązanie czasu wykonywania języka określa zachowanie. (W większości przypadków zgłaszany jest wyjątek czasu wykonywania).

Przykłady

Załóżmy, że chcesz podać alternatywną składnię uzyskiwania dostępu do wartości w słowniku, aby zamiast pisać sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" w Visual Basic), możesz napisać sampleDictionary.Text = "Sample text". Ponadto ta składnia musi być bez uwzględniania wielkości liter, więc sampleDictionary.Text jest ona równoważna sampleDictionary.text.

Poniższy przykład kodu przedstawia klasę DynamicDictionary , która pochodzi z DynamicObject klasy. Klasa DynamicDictionary zawiera obiekt Dictionary<string, object> typu (Dictionary(Of String, Object) w Visual Basic) do przechowywania par klucz-wartość i zastępuje TrySetMember metody i TryGetMember do obsługi nowej składni. Udostępnia Count również właściwość, która pokazuje, ile właściwości dynamicznych zawiera słownik.

// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // This property returns the number of elements
    // in the inner dictionary.
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }

    // If you try to get a value of a property
    // not defined in the class, this method is called.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        string name = binder.Name.ToLower();

        // If the property name is found in a dictionary,
        // set the result parameter to the property value and return true.
        // Otherwise, return false.
        return dictionary.TryGetValue(name, out result);
    }

    // If you try to set a value of a property that is
    // not defined in the class, this method is called.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        // Converting the property name to lowercase
        // so that property names become case-insensitive.
        dictionary[binder.Name.ToLower()] = value;

        // You can always add a value to a dictionary,
        // so this method always returns true.
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating a dynamic dictionary.
        dynamic person = new DynamicDictionary();

        // Adding new dynamic properties.
        // The TrySetMember method is called.
        person.FirstName = "Ellen";
        person.LastName = "Adams";

        // Getting values of the dynamic properties.
        // The TryGetMember method is called.
        // Note that property names are case-insensitive.
        Console.WriteLine(person.firstname + " " + person.lastname);

        // Getting the value of the Count property.
        // The TryGetMember is not called,
        // because the property is defined in the class.
        Console.WriteLine(
            "Number of dynamic properties:" + person.Count);

        // The following statement throws an exception at run time.
        // There is no "address" property,
        // so the TryGetMember method returns false and this causes a
        // RuntimeBinderException.
        // Console.WriteLine(person.address);
    }
}

// This example has the following output:
// Ellen Adams
// Number of dynamic properties: 2
' The class derived from DynamicObject.
Public Class DynamicDictionary
    Inherits DynamicObject

    ' The inner dictionary.
    Dim dictionary As New Dictionary(Of String, Object)

    ' This property returns the number of elements
    ' in the inner dictionary.
    ReadOnly Property Count As Integer
        Get
            Return dictionary.Count
        End Get
    End Property


    ' If you try to get a value of a property that is
    ' not defined in the class, this method is called.

    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder,
        ByRef result As Object) As Boolean

        ' Converting the property name to lowercase
        ' so that property names become case-insensitive.
        Dim name As String = binder.Name.ToLower()

        ' If the property name is found in a dictionary,
        ' set the result parameter to the property value and return true.
        ' Otherwise, return false.
        Return dictionary.TryGetValue(name, result)
    End Function

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

        ' Converting the property name to lowercase
        ' so that property names become case-insensitive.
        dictionary(binder.Name.ToLower()) = value

        ' You can always add a value to a dictionary,
        ' so this method always returns true.
        Return True
    End Function
End Class

Sub Main()
    ' Creating a dynamic dictionary.
    Dim person As Object = New DynamicDictionary()

    ' Adding new dynamic properties.
    ' The TrySetMember method is called.
    person.FirstName = "Ellen"
    person.LastName = "Adams"

    ' Getting values of the dynamic properties.
    ' The TryGetMember method is called.
    ' Note that property names are now case-insensitive,
    ' although they are case-sensitive in C#.
    Console.WriteLine(person.firstname & " " & person.lastname)

    ' Getting the value of the Count property.
    ' The TryGetMember is not called, 
    ' because the property is defined in the class.
    Console.WriteLine("Number of dynamic properties:" & person.Count)

    ' The following statement throws an exception at run time.
    ' There is no "address" property,
    ' so the TryGetMember method returns false and this causes
    ' a MissingMemberException.
    ' Console.WriteLine(person.address)
End Sub
' This examples has the following output:
' Ellen Adams
' Number of dynamic properties: 2

Uwagi

Klasy pochodzące z DynamicObject klasy mogą zastąpić tę metodę, aby określić sposób wykonywania operacji, które pobierają wartości składowe dla obiektu dynamicznego. Gdy metoda nie jest zastępowana, powiązanie czasu wykonywania języka określa zachowanie. (W większości przypadków zgłaszany jest wyjątek czasu wykonywania).

Ta metoda jest wywoływana, gdy istnieją instrukcje takie jak Console.WriteLine(sampleObject.SampleProperty), gdzie sampleObject jest wystąpieniem klasy pochodzącej DynamicObject z klasy.

Możesz również dodać własne elementy członkowskie do klas pochodnych z DynamicObject klasy. Jeśli klasa definiuje właściwości, a także zastępuje TrySetMember metodę, środowisko uruchomieniowe języka dynamicznego (DLR) najpierw używa powiązania języka, aby wyszukać statyczną definicję właściwości w klasie. Jeśli taka właściwość nie istnieje, biblioteka DLR wywołuje metodę TrySetMember .

Dotyczy