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);
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 동적 작업이 수행되는 멤버의 이름을 제공합니다. 예를 들어 클래스에서 binder.NameDynamicObject 파생된 클래스의 인스턴스인 sampleObject 문의 경우 Console.WriteLine(sampleObject.SampleProperty) "SampleProperty"를 반환합니다. 이 속성은 binder.IgnoreCase 멤버 이름이 대/소문자를 구분하는지 여부를 지정합니다.

result
Object

가져오기 작업의 결과입니다. 예를 들어 메서드가 속성에 대해 호출되는 경우 속성 값을 할당할 result수 있습니다.

반품

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

예제

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

다음 코드 예제에서는 DynamicDictionary 클래스에서 파생 된 클래스를 보여 줍니다 DynamicObject . DynamicDictionary 클래스는 키-값 쌍을 저장할 Dictionary<string, object> 형식(Visual Basic Dictionary(Of String, Object))의 개체를 포함하고 TrySetMemberTryGetMember 메서드를 재정의하여 새 구문을 지원합니다. 또한 사전에 포함된 동적 속성 수를 보여 주는 속성을 제공합니다 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됩니다.)

이 메서드는 클래스에서 DynamicObject 파생된 클래스의 인스턴스와 같은 Console.WriteLine(sampleObject.SampleProperty)문이 있을 sampleObject 때 호출됩니다.

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

적용 대상