DynamicObject 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
런타임에 동적 동작을 지정하기 위한 기본 클래스를 제공합니다. 이 클래스는 상속되어야 합니다. 직접 인스턴스화할 수 없습니다.
public ref class DynamicObject : System::Dynamic::IDynamicMetaObjectProvider
public class DynamicObject : System.Dynamic.IDynamicMetaObjectProvider
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a call site may require dynamic code generation.")]
public class DynamicObject : System.Dynamic.IDynamicMetaObjectProvider
[System.Serializable]
public class DynamicObject : System.Dynamic.IDynamicMetaObjectProvider
type DynamicObject = class
interface IDynamicMetaObjectProvider
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Creating a call site may require dynamic code generation.")>]
type DynamicObject = class
interface IDynamicMetaObjectProvider
[<System.Serializable>]
type DynamicObject = class
interface IDynamicMetaObjectProvider
Public Class DynamicObject
Implements IDynamicMetaObjectProvider
- 상속
-
DynamicObject
- 파생
- 특성
- 구현
예제
사전의 값에 액세스하기 위한 대체 구문을 제공하려는 경우 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))의 개체를 포함하고 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
자세한 예제는 C# 질문과 대답 블로그에서 DynamicObject를 사용하여 래퍼 만들기 를 참조하세요.
설명
이 DynamicObject 클래스를 사용하면 동적 개체에서 수행할 수 있는 작업과 해당 작업을 수행하는 방법을 정의할 수 있습니다. 예를 들어 개체 속성을 얻거나 설정하거나, 메서드를 호출하거나, 더하기 및 곱하기와 같은 표준 수학 연산을 수행하려고 할 때 발생하는 작업을 정의할 수 있습니다.
이 클래스는 라이브러리에 대한 보다 편리한 프로토콜을 만들려는 경우에 유용할 수 있습니다. 예를 들어 라이브러리 사용자가 같은 구문을 사용해야 하는 경우 다음과 같이 Scriptobj.SetProperty("Count", 1)scriptobj.Count = 1훨씬 더 간단한 구문을 사용하는 기능을 제공할 수 있습니다.
클래스의 DynamicObject 인스턴스를 직접 만들 수 없습니다. 동적 동작을 구현하려면 클래스에서 상속하고 필요한 메서드를 재정의 DynamicObject 할 수 있습니다. 예를 들어 속성을 설정하고 가져오기 위한 작업만 필요한 경우 해당 및 TryGetMember 메서드만 재정의할 TrySetMember 수 있습니다.
C#에서 클래스에서 파생된 클래스의 인스턴스에 대해 동적 동작을 DynamicObject 사용하도록 설정하려면 키워드를 dynamic 사용해야 합니다. 자세한 내용은 형식 동적 사용을 참조하세요.
Visual Basic에서 동적 작업은 지연 바인딩에서 지원됩니다. 자세한 내용은 초기 바인딩 및 지연 바인딩(Visual Basic)을 참조하세요.
다음 코드 예제에서는 클래스에서 DynamicObject 파생 된 클래스의 인스턴스를 만드는 방법을 보여 줍니다.
public class SampleDynamicObject : DynamicObject {}
//...
dynamic sampleObject = new SampleDynamicObject ();
Public Class SampleDynamicObject
Inherits DynamicObject
'...
Dim sampleObject As Object = New SampleDynamicObject()
클래스에서 DynamicObject 파생된 클래스에 고유한 멤버를 추가할 수도 있습니다. 클래스가 속성을 정의하고 메서드를 재정 TrySetMember 의하는 경우 DLR(동적 언어 런타임)은 먼저 언어 바인더를 사용하여 클래스에서 속성의 정적 정의를 찾습니다. 이러한 속성이 없으면 DLR에서 메서드를 호출합니다 TrySetMember .
이 클래스는 DynamicObject DLR 상호 운용성 모델을 지원하는 언어 간에 클래스의 DynamicObject 인스턴스를 공유할 수 있는 DLR 인터페이스IDynamicMetaObjectProvider를 구현합니다. 예를 들어 C#에서 클래스의 인스턴스를 DynamicObject 만든 다음 IronPython 함수에 전달할 수 있습니다. 자세한 내용은 동적 언어 런타임 개요를 참조하세요.
메모
런타임에 멤버만 추가 및 제거할 수 있지만 특정 작업을 정의할 필요가 없으며 정적 멤버가 없는 개체가 필요한 경우 클래스를 ExpandoObject 사용합니다.
동적 개체가 상호 운용성 프로토콜에 참여하는 방법을 정의해야 하거나 DLR 빠른 동적 디스패치 캐싱을 관리해야 하는 고급 시나리오가 있는 경우 인터페이스의 고유한 구현을 IDynamicMetaObjectProvider 만듭니다.
생성자
| Name | Description |
|---|---|
| DynamicObject() |
파생 형식이 형식의 새 인스턴스를 초기화할 수 있도록 합니다 DynamicObject . |
메서드
| Name | Description |
|---|---|
| Equals(Object) |
지정된 개체가 현재 개체와 같은지 여부를 확인합니다. (다음에서 상속됨 Object) |
| GetDynamicMemberNames() |
모든 동적 멤버 이름의 열거형을 반환합니다. |
| GetHashCode() |
기본 해시 함수로 사용됩니다. (다음에서 상속됨 Object) |
| GetMetaObject(Expression) |
DynamicMetaObject 동적 가상 메서드에 디스패치하는 기능을 제공합니다. 개체를 다른 DynamicMetaObject 개체 안에 캡슐화하여 개별 작업에 대한 사용자 지정 동작을 제공할 수 있습니다. 이 메서드는 언어 구현자에 대한 동적 언어 런타임 인프라를 지원하며 코드에서 직접 사용할 수 없습니다. |
| GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
| MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
| ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
| TryBinaryOperation(BinaryOperationBinder, Object, Object) |
이진 작업에 대한 구현을 제공합니다. 클래스에서 파생된 클래스는 이 메서드를 재정의 DynamicObject 하여 더하기 및 곱하기와 같은 작업에 대한 동적 동작을 지정할 수 있습니다. |
| TryConvert(ConvertBinder, Object) |
형식 변환 작업에 대한 구현을 제공합니다. 클래스에서 파생된 클래스는 개체를 DynamicObject 한 형식에서 다른 형식으로 변환하는 작업에 대한 동적 동작을 지정하기 위해 이 메서드를 재정의할 수 있습니다. |
| TryCreateInstance(CreateInstanceBinder, Object[], Object) |
동적 개체의 새 인스턴스를 초기화하는 작업에 대한 구현을 제공합니다. 이 메서드는 C# 또는 Visual Basic에서 사용할 수 없습니다. |
| TryDeleteIndex(DeleteIndexBinder, Object[]) |
인덱스별로 개체를 삭제하는 작업에 대한 구현을 제공합니다. 이 메서드는 C# 또는 Visual Basic에서 사용할 수 없습니다. |
| TryDeleteMember(DeleteMemberBinder) |
개체 멤버를 삭제하는 작업에 대한 구현을 제공합니다. 이 메서드는 C# 또는 Visual Basic에서 사용할 수 없습니다. |
| TryGetIndex(GetIndexBinder, Object[], Object) |
인덱스로 값을 가져오는 작업에 대한 구현을 제공합니다. 클래스에서 DynamicObject 파생된 클래스는 인덱싱 작업에 대한 동적 동작을 지정하기 위해 이 메서드를 재정의할 수 있습니다. |
| TryGetMember(GetMemberBinder, Object) |
멤버 값을 가져오는 작업에 대한 구현을 제공합니다. 클래스에서 파생 된 클래스 속성에 DynamicObject 대 한 값을 가져오는 등의 작업에 대 한 동적 동작을 지정 하려면이 메서드를 재정의할 수 있습니다. |
| TryInvoke(InvokeBinder, Object[], Object) |
개체를 호출하는 작업에 대한 구현을 제공합니다. 클래스에서 DynamicObject 파생된 클래스는 개체 또는 대리자 호출과 같은 작업에 대한 동적 동작을 지정하기 위해 이 메서드를 재정의할 수 있습니다. |
| TryInvokeMember(InvokeMemberBinder, Object[], Object) |
멤버를 호출하는 작업에 대한 구현을 제공합니다. 클래스에서 DynamicObject 파생된 클래스는 메서드 호출과 같은 작업에 대한 동적 동작을 지정하기 위해 이 메서드를 재정의할 수 있습니다. |
| TrySetIndex(SetIndexBinder, Object[], Object) |
인덱스별로 값을 설정하는 작업에 대한 구현을 제공합니다. 클래스에서 DynamicObject 파생된 클래스는 지정된 인덱스로 개체에 액세스하는 작업에 대한 동적 동작을 지정하기 위해 이 메서드를 재정의할 수 있습니다. |
| TrySetMember(SetMemberBinder, Object) |
멤버 값을 설정하는 작업에 대한 구현을 제공합니다. 클래스에서 파생 된 클래스 속성에 DynamicObject 대 한 값을 설정 하는 등의 작업에 대 한 동적 동작을 지정 하려면이 메서드를 재정의할 수 있습니다. |
| TryUnaryOperation(UnaryOperationBinder, Object) |
단항 작업에 대한 구현을 제공합니다. 클래스에서 파생된 클래스는 이 메서드를 재정의 DynamicObject 하여 부정, 증가 또는 감소와 같은 작업에 대한 동적 동작을 지정할 수 있습니다. |