DynamicObject.TrySetMember(SetMemberBinder, Object) 方法

定义

为设置成员值的操作提供实现。Provides the implementation for operations that set member values. DynamicObject 类派生的类可以重写此方法,以便为诸如设置属性值这样的操作指定动态行为。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as setting a value for a property.

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

提供有关调用了动态操作的对象的信息。Provides information about the object that called the dynamic operation. binder.Name 属性提供将该值分配到的成员的名称。The binder.Name property provides the name of the member to which the value is being assigned. 例如,对于 sampleObject.SampleProperty = "Test" 语句(其中 sampleObject 是派生自 DynamicObject 类的类的实例),binder.Name 返回“SampleProperty”。For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the DynamicObject class, binder.Name returns "SampleProperty". binder.IgnoreCase 属性指定成员名称是否区分大小写。The binder.IgnoreCase property specifies whether the member name is case-sensitive.

value
Object

要为成员设置的值。The value to set to the member. 例如,对于 sampleObject.SampleProperty = "Test" 语句(其中 sampleObject 是派生自 DynamicObject 类的类的实例),value 为 "Test"。For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the DynamicObject class, the value is "Test".

返回

Boolean

如果操作成功,则为 true;否则为 falsetrue if the operation is successful; otherwise, false. 如果此方法返回 false,则该语言的运行时联编程序将决定行为。If this method returns false, the run-time binder of the language determines the behavior. (大多数情况下,将引发语言特定的运行时异常。)(In most cases, a language-specific run-time exception is thrown.)

示例

假设你想要提供用于访问字典中的值的替代语法,以便可以编写,而不是 sampleDictionary["Text"] = "Sample text" sampleDictionary("Text") = "Sample text" 在 Visual Basic) 中写入 (sampleDictionary.Text = "Sample text"Assume that you want to provide alternative syntax for accessing values in a dictionary, so that instead of writing sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" in Visual Basic), you can write sampleDictionary.Text = "Sample text". 此外,此语法必须不区分大小写,因此 sampleDictionary.Text 等效于 sampleDictionary.textAlso, this syntax must be case-insensitive, so that sampleDictionary.Text is equivalent to sampleDictionary.text.

下面的代码示例演示 DynamicDictionary 类,该类派生自 DynamicObject 类。The following code example demonstrates the DynamicDictionary class, which is derived from the DynamicObject class. DynamicDictionary类包含 Dictionary<string, object> Visual Basic) 中 (类型的对象 Dictionary(Of String, Object) ,用于存储键/值对,并重写 TrySetMemberTryGetMember 方法以支持新的语法。The DynamicDictionary class contains an object of the Dictionary<string, object> type (Dictionary(Of String, Object) in Visual Basic) to store the key-value pairs, and overrides the TrySetMember and TryGetMember methods to support the new syntax. 它还提供了一个 Count 属性,该属性显示字典包含的动态属性的数目。It also provides a Count property, which shows how many dynamic properties the dictionary contains.

// 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 可以重写此方法,以指定如何为动态对象执行将值设置为成员的操作。Classes derived from the DynamicObject class can override this method to specify how operations that set a value to a member should be performed for a dynamic object. 如果未重写此方法,则该语言的运行时联编程序将确定行为。When the method is not overridden, the run-time binder of the language determines the behavior. (大多数情况下,将引发语言特定的运行时异常。)(In most cases, a language-specific run-time exception is thrown.)

当你具有类似的语句时调用此方法 sampleObject.SampleProperty = "Test" ,其中 sampleObject 是派生自类的类的实例 DynamicObjectThis method is called when you have statements like sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class that is derived from the DynamicObject class.

你还可以将自己的成员添加到从类派生的类 DynamicObjectYou can also add your own members to classes derived from the DynamicObject class. 如果你的类定义了属性,并且还重写了 TrySetMember 方法,则动态语言运行时 (DLR) 首先使用语言联编程序来查找类中属性的静态定义。If your class defines properties and also overrides the TrySetMember method, the dynamic language runtime (DLR) first uses the language binder to look for a static definition of a property in the class. 如果没有此类属性,则 DLR 会调用 TrySetMember 方法。If there is no such property, the DLR calls the TrySetMember method.

适用于