DynamicObject DynamicObject DynamicObject DynamicObject Class

定義

提供基底類別,以便指定在執行階段時的動態行為。Provides a base class for specifying dynamic behavior at run time. 這個類別必須是繼承類別,您無法直接將其執行個體化。This class must be inherited from; you cannot instantiate it directly.

public ref class DynamicObject : System::Dynamic::IDynamicMetaObjectProvider
[System.Serializable]
public class DynamicObject : System.Dynamic.IDynamicMetaObjectProvider
type DynamicObject = class
    interface IDynamicMetaObjectProvider
Public Class DynamicObject
Implements IDynamicMetaObjectProvider
繼承
DynamicObjectDynamicObjectDynamicObjectDynamicObject
衍生
屬性
實作

範例

假設您想要提供替代語法來存取值在字典中,也因此的書寫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, you want this syntax to 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>型別 (Dictionary(Of String, Object)在 Visual Basic 中) 來儲存索引鍵 / 值組,並覆寫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 C# 常見問題集部落格上。For more examples, see Creating Wrappers with DynamicObject on the C# Frequently Asked Questions blog.

備註

DynamicObject類別可讓您定義可以在動態物件上執行哪些作業,以及如何執行這些作業。The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. 例如,您可以定義當您嘗試取得或設定物件屬性、 呼叫方法,或執行標準的數學運算,例如加法和乘法時,會發生什麼事。For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.

這個類別可以是很有用,如果您想要建立之程式庫更方便的通訊協定。This class can be useful if you want to create a more convenient protocol for a library. 例如,如果您的程式庫的使用者必須使用下列語法: Scriptobj.SetProperty("Count", 1),您可以讓您能夠使用更簡單的語法,例如scriptobj.Count = 1For example, if users of your library have to use syntax like Scriptobj.SetProperty("Count", 1), you can provide the ability to use much simpler syntax, like scriptobj.Count = 1.

您無法直接建立的執行個體DynamicObject類別。You cannot directly create an instance of the DynamicObject class. 若要實作的動態行為,您可能想要繼承DynamicObject類別並覆寫所需的方法。To implement the dynamic behavior, you may want to inherit from the DynamicObject class and override necessary methods. 例如,如果您需要的設定和取得屬性的唯一作業,您可以覆寫只TrySetMemberTryGetMember方法。For example, if you need only operations for setting and getting properties, you can override just the TrySetMember and TryGetMember methods.

在 C# 中,來啟用從衍生類別的執行個體的動態行為DynamicObject類別,您必須使用dynamic關鍵字。In C#, to enable dynamic behavior for instances of classes derived from the DynamicObject class, you must use the dynamic keyword. 如需詳細資訊,請參閱使用動態類型For more information, see Using Type dynamic.

在 Visual Basic 中的晚期繫結支援動態作業。In Visual Basic, dynamic operations are supported by late binding. 如需詳細資訊,請參閱 < 早期和晚期繫結For more information, see Early and Late Binding.

下列程式碼範例示範如何建立衍生自類別的執行個體DynamicObject類別。The following code example demonstrates how to create an instance of a class that is derived from the DynamicObject class.

public class SampleDynamicObject : DynamicObject {}  
//...  
dynamic sampleObject = new SampleDynamicObject ();  
Public Class SampleDynamicObject   
    Inherits DynamicObject  
'...  
Dim sampleObject As Object = New SampleDynamicObject()  

您也可以將您自己的成員加入衍生自類別DynamicObject類別。You 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. 如果沒有這類屬性,會呼叫 DLRTrySetMember方法。If there is no such property, the DLR calls the TrySetMember method.

DynamicObject類別會實作 DLR 介面IDynamicMetaObjectProvider,這可讓您共用的執行個體DynamicObject支援 DLR 互通性模型的語言之間的類別。The DynamicObject class implements the DLR interface IDynamicMetaObjectProvider, which enables you to share instances of the DynamicObject class between languages that support the DLR interoperability model. 例如,您可以在其中建立的執行個體DynamicObject類別在 C# 中,並再將它傳遞給 IronPython 函式。For example, you can create an instance of the DynamicObject class in C# and then pass it to an IronPython function. 如需詳細資訊,請參閱 < Dynamic Language Runtime 概觀For more information, see Dynamic Language Runtime Overview.

注意

如果您有一個簡單的案例,您需要的物件,但是,只能新增和移除成員,在執行階段,不需要定義特定的作業,而且不會不有靜態成員,使用ExpandoObject類別。If you have a simple scenario in which you need an object that can only add and remove members at run time but that does not need to define specific operations and does not have static members, use the ExpandoObject class.

如果您有更進階的案例,您要定義參與互通性通訊協定,或您要管理快取的 DLR 快速動態分派動態物件的方式,建立您自己實作IDynamicMetaObjectProvider介面。If you have a more advanced scenario in which you need to define how dynamic objects participate in the interoperability protocol, or you need to manage DLR fast dynamic dispatch caching, create your own implementation of the IDynamicMetaObjectProvider interface.

建構函式

DynamicObject() DynamicObject() DynamicObject() DynamicObject()

讓衍生型別得以初始化 DynamicObject 型別的新執行個體。Enables derived types to initialize a new instance of the DynamicObject type.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetDynamicMemberNames() GetDynamicMemberNames() GetDynamicMemberNames() GetDynamicMemberNames()

傳回所有動態成員名稱的列舉型別。Returns the enumeration of all dynamic member names.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetMetaObject(Expression) GetMetaObject(Expression) GetMetaObject(Expression) GetMetaObject(Expression)

提供分派給動態虛擬方法的 DynamicMetaObjectProvides a DynamicMetaObject that dispatches to the dynamic virtual methods. 此物件可以封裝在另一個 DynamicMetaObject 內部,以提供個別動作的自訂行為。The object can be encapsulated inside another DynamicMetaObject to provide custom behavior for individual actions. 這個方法支援語言實作者適用的動態語言執行階段基礎結構,但不建議直接在程式碼中使用。This method supports the Dynamic Language Runtime infrastructure for language implementers and it is not intended to be used directly from your code.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TryBinaryOperation(BinaryOperationBinder, Object, Object) TryBinaryOperation(BinaryOperationBinder, Object, Object) TryBinaryOperation(BinaryOperationBinder, Object, Object) TryBinaryOperation(BinaryOperationBinder, Object, Object)

提供二進位運算的實作。Provides implementation for binary operations. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定加法和乘法這類運算的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as addition and multiplication.

TryConvert(ConvertBinder, Object) TryConvert(ConvertBinder, Object) TryConvert(ConvertBinder, Object) TryConvert(ConvertBinder, Object)

提供型別轉換作業的實作。Provides implementation for type conversion operations. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定物件型別轉換作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations that convert an object from one type to another.

TryCreateInstance(CreateInstanceBinder, Object[], Object) TryCreateInstance(CreateInstanceBinder, Object[], Object) TryCreateInstance(CreateInstanceBinder, Object[], Object) TryCreateInstance(CreateInstanceBinder, Object[], Object)

提供作業的實作,這些作業會初始化動態物件的新執行個體。Provides the implementation for operations that initialize a new instance of a dynamic object. 這個方法並不適用於 C# 或 Visual Basic。This method is not intended for use in C# or Visual Basic.

TryDeleteIndex(DeleteIndexBinder, Object[]) TryDeleteIndex(DeleteIndexBinder, Object[]) TryDeleteIndex(DeleteIndexBinder, Object[]) TryDeleteIndex(DeleteIndexBinder, Object[])

提供依索引刪除物件之作業的實作。Provides the implementation for operations that delete an object by index. 這個方法並不適用於 C# 或 Visual Basic。This method is not intended for use in C# or Visual Basic.

TryDeleteMember(DeleteMemberBinder) TryDeleteMember(DeleteMemberBinder) TryDeleteMember(DeleteMemberBinder) TryDeleteMember(DeleteMemberBinder)

提供刪除物件成員之作業的實作。Provides the implementation for operations that delete an object member. 這個方法並不適用於 C# 或 Visual Basic。This method is not intended for use in C# or Visual Basic.

TryGetIndex(GetIndexBinder, Object[], Object) TryGetIndex(GetIndexBinder, Object[], Object) TryGetIndex(GetIndexBinder, Object[], Object) TryGetIndex(GetIndexBinder, Object[], Object)

提供依索引取得值之作業的實作。Provides the implementation for operations that get a value by index. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定索引作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for indexing operations.

TryGetMember(GetMemberBinder, Object) TryGetMember(GetMemberBinder, Object) TryGetMember(GetMemberBinder, Object) TryGetMember(GetMemberBinder, Object)

提供取得成員值之作業的實作。Provides the implementation for operations that get member values. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定取得屬性值這類作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.

TryInvoke(InvokeBinder, Object[], Object) TryInvoke(InvokeBinder, Object[], Object) TryInvoke(InvokeBinder, Object[], Object) TryInvoke(InvokeBinder, Object[], Object)

提供叫用物件之作業的實作。Provides the implementation for operations that invoke an object. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定叫用物件或委派這類作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as invoking an object or a delegate.

TryInvokeMember(InvokeMemberBinder, Object[], Object) TryInvokeMember(InvokeMemberBinder, Object[], Object) TryInvokeMember(InvokeMemberBinder, Object[], Object) TryInvokeMember(InvokeMemberBinder, Object[], Object)

提供叫用成員之作業的實作。Provides the implementation for operations that invoke a member. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定呼叫方法這類作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as calling a method.

TrySetIndex(SetIndexBinder, Object[], Object) TrySetIndex(SetIndexBinder, Object[], Object) TrySetIndex(SetIndexBinder, Object[], Object) TrySetIndex(SetIndexBinder, Object[], Object)

提供依索引設定值之作業的實作。Provides the implementation for operations that set a value by index. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定依指定之索引存取物件之作業的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations that access objects by a specified index.

TrySetMember(SetMemberBinder, Object) TrySetMember(SetMemberBinder, Object) TrySetMember(SetMemberBinder, Object) 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.

TryUnaryOperation(UnaryOperationBinder, Object) TryUnaryOperation(UnaryOperationBinder, Object) TryUnaryOperation(UnaryOperationBinder, Object) TryUnaryOperation(UnaryOperationBinder, Object)

提供一元運算的實作。Provides implementation for unary operations. 衍生自 DynamicObject 類別的類別可以覆寫這個方法,以指定負號、遞增或遞減這類運算的動態行為。Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as negation, increment, or decrement.

適用於