DynamicObject.TryGetMember(GetMemberBinder, Object) Метод

Определение

Предоставляет реализацию для операций, получающих значения членов. Классы, производные от класса DynamicObject, могут переопределять этот метод, чтобы задать динамическое поведение для таких операций, как получение значения свойства.

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

Параметры

binder
GetMemberBinder

Предоставляет сведения об объекте, вызвавшем динамическую операцию. Свойство binder.Name предоставляет имя элемента, с которым выполняется динамическая операция. Например, для Console.WriteLine(sampleObject.SampleProperty) оператора , где sampleObject является экземпляром класса, производного от DynamicObject класса , binder.Name возвращается "SampleProperty". Свойство binder.IgnoreCase указывает, учитывается ли имя элемента с учетом регистра.

result
Object

Результат операции получения. Например, если для свойства вызывается метод, можно присвоить свойству значение result.

Возвращаемое значение

Значение true, если операция выполнена успешно; в противном случае — значение false. Если данный метод возвращает значение false, поведение определяется связывателем среды языка. (В большинстве случаев создается исключение во время выполнения).

Примеры

Предположим, что вы хотите предоставить альтернативный синтаксис для доступа к значениям в словаре, чтобы вместо записи sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" в Visual Basic) можно было написать sampleDictionary.Text = "Sample text". Кроме того, этот синтаксис должен не учитывать регистр, поэтому sampleDictionary.Text это эквивалентно sampleDictionary.text.

В следующем примере кода демонстрируется DynamicDictionary класс , производный DynamicObject от класса . Класс DynamicDictionary содержит объект Dictionary<string, object> типа (Dictionary(Of String, Object) в Visual Basic) для хранения пар "ключ-значение" и переопределяет TrySetMember методы и TryGetMember для поддержки нового синтаксиса. Он также предоставляет Count свойство , которое показывает, сколько динамических свойств содержит словарь.

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

Комментарии

Классы, производные DynamicObject от класса , могут переопределять этот метод, чтобы указать, как операции, получающие значения элементов, должны выполняться для динамического объекта. Если метод не переопределен, связыватель времени выполнения языка определяет поведение. (В большинстве случаев создается исключение во время выполнения).

Этот метод вызывается при наличии таких операторов, как Console.WriteLine(sampleObject.SampleProperty), где sampleObject является экземпляром класса, производного от DynamicObject класса .

Вы также можете добавить собственные члены в классы, производные DynamicObject от класса . Если класс определяет свойства, а также переопределяет TrySetMember метод, то динамическая языковая среда выполнения (DLR) сначала использует связыватель языка для поиска статического определения свойства в классе . Если такого свойства нет, DLR вызывает TrySetMember метод .

Применяется к