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 는 클래스 binder.Name 에서 DynamicObject 파생된 클래스의 instance "SampleProperty"를 반환합니다. 속성은 binder.IgnoreCase 멤버 이름이 대/소문자를 구분하는지 여부를 지정합니다.

value
Object

멤버에 설정할 값입니다. 예를 들어 의 경우 sampleObject.SampleProperty = "Test"여기서 sampleObject 는 클래스에서 DynamicObjectvalue 파생된 클래스의 instance "Test"입니다.

반환

작업에 성공하면 true이고, 그렇지 않으면 false입니다. 이 메서드가 false를 반환하는 경우 언어의 런타임 바인더에 따라 동작이 결정됩니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

예제

(Visual Basic에서는 )sampleDictionary("Text") = "Sample text"를 작성하는 대신 를 작성 sampleDictionary["Text"] = "Sample text"sampleDictionary.Text = "Sample text"할 수 있도록 사전의 값에 액세스하기 위한 대체 구문을 제공하려고 합니다. 또한 이 구문은 대/소문자를 구분하지 않아야 하므로 와 sampleDictionary.Text 동일합니다 sampleDictionary.text.

다음 코드 예제에서는 DynamicDictionary 클래스에서 파생 된 클래스를 보여 줍니다 DynamicObject . 클래스는 DynamicDictionary 키-값 쌍을 저장할 형식(Dictionary(Of String, Object)Visual Basic의 경우)의 Dictionary<string, object> 개체를 포함하고 및 TryGetMember 메서드를 재정 TrySetMember 의하여 새 구문을 지원합니다. 또한 사전에 포함된 동적 속성 수를 보여 주는 속성을 제공합니다 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 하여 동적 개체에 대해 값을 멤버로 설정하는 작업을 수행하는 방법을 지정할 수 있습니다. 메서드를 재정의하지 않으면 언어의 런타임 바인더가 동작을 결정합니다. 대부분의 경우 언어별 런타임 예외가 throw됩니다.

이 메서드는 와 같은 sampleObject.SampleProperty = "Test"문이 있을 때 호출됩니다. 여기서 sampleObject 는 클래스에서 DynamicObject 파생된 클래스의 instance.

클래스에서 DynamicObject 파생된 클래스에 고유한 멤버를 추가할 수도 있습니다. 클래스가 속성을 정의하고 메서드를 재정 TrySetMember 의하는 경우 DLR(동적 언어 런타임)은 먼저 언어 바인더를 사용하여 클래스에서 속성의 정적 정의를 찾습니다. 이러한 속성이 없으면 DLR은 메서드를 호출합니다 TrySetMember .

적용 대상