DynamicObject.TrySetMember(SetMemberBinder, Object) Метод

Определение

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

public:
 virtual bool TrySetMember(System::Dynamic::SetMemberBinder ^ binder, System::Object ^ value);
public virtual bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value);
public virtual bool TrySetMember(System.Dynamic.SetMemberBinder binder, object? value);
abstract member TrySetMember : System.Dynamic.SetMemberBinder * obj -> bool
override this.TrySetMember : System.Dynamic.SetMemberBinder * obj -> bool
Public Overridable Function TrySetMember (binder As SetMemberBinder, value As Object) As Boolean

Параметры

binder
SetMemberBinder

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

value
Object

Значение, заданное элементом. Например, например sampleObject.SampleProperty = "Test", где sampleObject является экземпляр класса, производный от DynamicObject класса, value имеет значение Test.

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

Значение 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 класса, могут переопределить этот метод, чтобы указать, как операции, устанавливающие значение для элемента, должны выполняться для динамического объекта. Если метод не переопределен, привязка во время выполнения языка определяет поведение. (В большинстве случаев создается исключение времени выполнения для конкретного языка.)

Этот метод вызывается, если у вас есть такие операторы, как sampleObject.SampleProperty = "Test", где sampleObject является экземпляр класса, производный от DynamicObject класса.

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

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