ExpandoObject 類別

定義

代表可在執行階段以動態方式加入和移除其成員的物件。Represents an object whose members can be dynamically added and removed at run time.

public ref class ExpandoObject sealed : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<System::String ^, System::Object ^>>, System::Collections::Generic::IDictionary<System::String ^, System::Object ^>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<System::String ^, System::Object ^>>, System::ComponentModel::INotifyPropertyChanged, System::Dynamic::IDynamicMetaObjectProvider
public sealed class ExpandoObject : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string,object>>, System.Collections.Generic.IDictionary<string,object>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,object>>, System.ComponentModel.INotifyPropertyChanged, System.Dynamic.IDynamicMetaObjectProvider
type ExpandoObject = class
    interface IDynamicMetaObjectProvider
    interface IDictionary<string, obj>
    interface INotifyPropertyChanged
    interface ICollection<KeyValuePair<string, obj>>
    interface seq<KeyValuePair<string, obj>>
    interface IEnumerable
Public NotInheritable Class ExpandoObject
Implements ICollection(Of KeyValuePair(Of String, Object)), IDictionary(Of String, Object), IDynamicMetaObjectProvider, IEnumerable(Of KeyValuePair(Of String, Object)), INotifyPropertyChanged
繼承
ExpandoObject
實作

備註

ExpandoObject 類別可讓您在執行時間新增和刪除其實例的成員,以及設定和取得這些成員的值。The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. 這個類別支援動態系結,可讓您使用標準語法(例如 sampleObject.sampleMember),而不是像 sampleObject.GetAttribute("sampleMember")等較複雜的語法。This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

ExpandoObject 類別會實作為標準動態語言執行時間(DLR)介面 IDynamicMetaObjectProvider,可讓您在支援 DLR 互通性模型的語言之間共用 ExpandoObject 類別的實例。The ExpandoObject class implements the standard Dynamic Language Runtime (DLR) interface IDynamicMetaObjectProvider, which enables you to share instances of the ExpandoObject class between languages that support the DLR interoperability model. 例如,您可以在中C#建立 ExpandoObject 類別的實例,然後將它傳遞至 IronPython 函數。For example, you can create an instance of the ExpandoObject class in C# and then pass it to an IronPython function. 如需詳細資訊,請參閱動態語言運行時間C#總覽和簡介 ExpandoObject常見問題網站。For more information, see Dynamic Language Runtime Overview and Introducing the ExpandoObject on the C# Frequently Asked Questions Web site.

ExpandoObject 類別是動態物件概念的執行,可讓您取得、設定和叫用成員。The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members. 如果您想要定義具有自己的動態分派語義的類型,請使用 DynamicObject 類別。If you want to define types that have their own dynamic dispatch semantics, use the DynamicObject class. 如果您想要定義動態物件如何參與互通性通訊協定,以及管理 DLR 快速動態分派快取,請建立您自己的 IDynamicMetaObjectProvider 介面的執行。If you want to define how dynamic objects participate in the interoperability protocol and manage DLR fast dynamic dispatch caching, create your own implementation of the IDynamicMetaObjectProvider interface.

建立實例Creating an Instance

在C#中,若要啟用 ExpandoObject 類別之實例的晚期繫結,您必須使用 dynamic 關鍵字。In C#, to enable late binding for an instance of the ExpandoObject 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.

下列程式碼範例示範如何建立 ExpandoObject 類別的實例。The following code example demonstrates how to create an instance of the ExpandoObject class.

dynamic sampleObject = new ExpandoObject();
Dim sampleObject As Object = New ExpandoObject()

加入新成員Adding New Members

您可以將屬性、方法和事件加入至 ExpandoObject 類別的實例。You can add properties, methods, and events to instances of the ExpandoObject class.

下列程式碼範例示範如何將新的屬性加入至 ExpandoObject 類別的實例。The following code example demonstrates how to add a new property to an instance of the ExpandoObject class.

sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.GetType());
// This code example produces the following output:
// Dynamic Property
// System.String
sampleObject.Test = "Dynamic Property"
Console.WriteLine(sampleObject.test)
Console.WriteLine(sampleObject.test.GetType())
' This code example produces the following output:
' Dynamic Property
' System.String

這些方法代表儲存為委派的 lambda 運算式,可在需要時叫用。The methods represent lambda expressions that are stored as delegates, which can be invoked when they are needed. 下列程式碼範例示範如何新增方法,以遞增動態屬性的值。The following code example demonstrates how to add a method that increments a value of the dynamic property.

sampleObject.number = 10;
sampleObject.Increment = (Action)(() => { sampleObject.number++; });

// Before calling the Increment method.
Console.WriteLine(sampleObject.number);

sampleObject.Increment();

// After calling the Increment method.
Console.WriteLine(sampleObject.number);
// This code example produces the following output:
// 10
// 11
sampleObject.Number = 10
sampleObject.Increment = Function() sampleObject.Number + 1
' Before calling the Increment method.
Console.WriteLine(sampleObject.number)

sampleObject.Increment.Invoke()

' After calling the Increment method.
Console.WriteLine(sampleObject.number)
' This code example produces the following output:
' 10
' 11

下列程式碼範例示範如何將事件加入至 ExpandoObject 類別的實例。The following code example demonstrates how to add an event to an instance of the ExpandoObject class.

class Program  
{  
    static void Main(string[] args)  
    {  
        dynamic sampleObject = new ExpandoObject();  
  
        // Create a new event and initialize it with null.  
        sampleObject.sampleEvent = null;  
  
        // Add an event handler.  
        sampleObject.sampleEvent += new EventHandler(SampleHandler);  
  
        // Raise an event for testing purposes.  
        sampleObject.sampleEvent(sampleObject, new EventArgs());  
   }  
  
    // Event handler.  
    static void SampleHandler(object sender, EventArgs e)  
    {  
        Console.WriteLine("SampleHandler for {0} event", sender);  
    }  
}  
// This code example produces the following output:  
// SampleHandler for System.Dynamic.ExpandoObject event.  
Module Module1  
  
Sub Main()  
    Dim sampleObject As Object = New ExpandoObject()  
  
    ' Create a new event and initialize it with null.  
    sampleObject.sampleEvent = Nothing  
  
    ' Add an event handler.  
    Dim handler As EventHandler = AddressOf SampleHandler  
    sampleObject.sampleEvent =   
        [Delegate].Combine(sampleObject.sampleEvent, handler)  
  
    ' Raise an event for testing purposes.  
    sampleObject.sampleEvent.Invoke(sampleObject, New EventArgs())  
  
End Sub  
  
' Event handler.  
Sub SampleHandler(ByVal sender As Object, ByVal e As EventArgs)  
    Console.WriteLine("SampleHandler for {0} event", sender)  
End Sub  
  
' This code example produces the following output:  
' SampleHandler for System.Dynamic.ExpandoObject event.  
  
End Module  

當做參數傳遞Passing As a Parameter

您可以將 ExpandoObject 類別的實例當做參數傳遞。You can pass instances of the ExpandoObject class as parameters. 請注意,這些實例會被視為中的C#動態物件,以及 Visual Basic 中的晚期繫結物件。Note that these instances are treated as dynamic objects in C# and late-bound objects in Visual Basic. 這表示您沒有物件成員的 IntelliSense,而且當您呼叫不存在的成員時,不會收到編譯器錯誤。This means that you do not have IntelliSense for object members and you do not receive compiler errors when you call non-existent members. 如果您呼叫的成員不存在,就會發生例外狀況。If you call a member that does not exist, an exception occurs.

下列程式碼範例會示範如何建立和使用方法,以列印屬性的名稱和值。The following code example demonstrates how you can create and use a method to print the names and values of properties.

class Program
{
    static void Main(string[] args)
    {
        dynamic employee, manager;

        employee = new ExpandoObject();
        employee.Name = "John Smith";
        employee.Age = 33;

        manager = new ExpandoObject();
        manager.Name = "Allison Brown";
        manager.Age = 42;
        manager.TeamSize = 10;

        WritePerson(manager);
        WritePerson(employee);
    }
    private static void WritePerson(dynamic person)
    {
        Console.WriteLine("{0} is {1} years old.",
                          person.Name, person.Age);
        // The following statement causes an exception
        // if you pass the employee object.
        // Console.WriteLine("Manages {0} people", person.TeamSize);
    }
}
// This code example produces the following output:
// John Smith is 33 years old.
// Allison Brown is 42 years old.
Sub Main()
    Dim employee, manager As Object

    employee = New ExpandoObject()
    employee.Name = "John Smith"
    employee.Age = 33

    manager = New ExpandoObject()
    manager.Name = "Allison Brown"
    manager.Age = 42
    manager.TeamSize = 10

    WritePerson(manager)
    WritePerson(employee)
End Sub

Private Sub WritePerson(ByVal person As Object)

    Console.WriteLine("{0} is {1} years old.",
                      person.Name, person.Age)
    ' The following statement causes an exception
    ' if you pass the employee object.
    ' Console.WriteLine("Manages {0} people", person.TeamSize)

End Sub

列舉和刪除成員Enumerating and Deleting Members

ExpandoObject 類別會實作 IDictionary<String, Object> 介面。The ExpandoObject class implements the IDictionary<String, Object> interface. 這可讓您在執行時間將加入至 ExpandoObject 類別實例的成員列舉。This enables enumeration of members added to the instance of the ExpandoObject class at run time. 如果您在編譯時期不知道實例可能擁有的成員,這就很有用。This can be useful if you do not know at compile time what members an instance might have.

下列程式碼範例會示範如何將 ExpandoObject 類別的實例轉換為 IDictionary<TKey,TValue> 介面,並列舉實例的成員。The following code example shows how you can cast an instance of the ExpandoObject class to the IDictionary<TKey,TValue> interface and enumerate the instance's members.

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<String, Object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
Dim employee As Object = New ExpandoObject()
employee.Name = "John Smith"
employee.Age = 33
For Each member In CType(employee, IDictionary(Of String, Object))
    Console.WriteLine(member.Key & ": " & member.Value)
Next
' This code example produces the following output:
' Name: John Smith
' Age: 33

在沒有刪除成員(例如C#和 Visual Basic)語法的語言中,您可以將 ExpandoObject 的實例隱含地轉換為 IDictionary<String, Object> 介面,然後將該成員刪除為索引鍵/值組,藉以刪除成員。In languages that do not have syntax for deleting members (such as C# and Visual Basic), you can delete a member by implicitly casting an instance of the ExpandoObject to the IDictionary<String, Object> interface and then deleting the member as a key/value pair. 這在下列範例中顯示。This is shown in the following example.

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
Dim employee As Object = New ExpandoObject()
employee.Name = "John Smith"
CType(employee, IDictionary(Of String, Object)).Remove("Name")

接收屬性變更的通知Receiving Notifications of Property Changes

ExpandoObject 類別會執行 INotifyPropertyChanged 介面,而且可以在加入、刪除或修改成員時引發 PropertyChanged 事件。The ExpandoObject class implements the INotifyPropertyChanged interface and can raise a PropertyChanged event when a member is added, deleted, or modified. 這可讓 ExpandoObject 類別與 Windows Presentation Foundation (WPF)資料系結,以及其他需要物件內容中變更通知的環境進行整合。This enables ExpandoObject class integration with Windows Presentation Foundation (WPF) data binding and other environments that require notification about changes in the object content.

下列程式碼範例示範如何建立 PropertyChanged 事件的事件處理常式。The following code example demonstrates how to create an event handler for the PropertyChanged event.

// Add "using System.ComponentModel;" line 
// to the beginning of the file.
class Program
{
    static void Test()
    {
        dynamic employee = new ExpandoObject();
        ((INotifyPropertyChanged)employee).PropertyChanged +=
            new PropertyChangedEventHandler(HandlePropertyChanges);
        employee.Name = "John Smith";
    }

    private static void HandlePropertyChanges(
        object sender, PropertyChangedEventArgs e)
    {
        Console.WriteLine("{0} has changed.", e.PropertyName);
    }
}
' Add "Imports System.ComponentModel" line 
' to the beginning of the file.
Sub Main()
    Dim employee As Object = New ExpandoObject
    AddHandler CType(
        employee, INotifyPropertyChanged).PropertyChanged,
        AddressOf HandlePropertyChanges
    employee.Name = "John Smith"
End Sub

Private Sub HandlePropertyChanges(
       ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
    Console.WriteLine("{0} has changed.", e.PropertyName)
End Sub

建構函式

ExpandoObject()

初始化沒有成員的新 ExpandoObjectInitializes a new ExpandoObject that does not have members.

方法

Equals(Object)

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

(繼承來源 Object)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

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

(繼承來源 Object)
MemberwiseClone()

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

(繼承來源 Object)
ToString()

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

(繼承來源 Object)

明確介面實作

ICollection<KeyValuePair<String,Object>>.Add(KeyValuePair<String,Object>)

將指定的值加入至具有指定索引鍵的 ICollection<T>Adds the specified value to the ICollection<T> that has the specified key.

ICollection<KeyValuePair<String,Object>>.Clear()

移除集合的所有項目。Removes all items from the collection.

ICollection<KeyValuePair<String,Object>>.Contains(KeyValuePair<String,Object>)

判斷 ICollection<T> 是否包含特定索引鍵和值。Determines whether the ICollection<T> contains a specific key and value.

ICollection<KeyValuePair<String,Object>>.CopyTo(KeyValuePair<String,Object>[], Int32)

從指定的陣列索引處開始,將 ICollection<T> 的項目複製到 KeyValuePair<TKey,TValue> 類型的陣列。Copies the elements of the ICollection<T> to an array of type KeyValuePair<TKey,TValue>, starting at the specified array index.

ICollection<KeyValuePair<String,Object>>.Count

取得 ICollection<T> 中的項目數目。Gets the number of elements in the ICollection<T>.

ICollection<KeyValuePair<String,Object>>.IsReadOnly

取得值,指出 ICollection<T> 是否唯讀。Gets a value indicating whether the ICollection<T> is read-only.

ICollection<KeyValuePair<String,Object>>.Remove(KeyValuePair<String,Object>)

從集合移除索引鍵和值。Removes a key and value from the collection.

IDictionary<String,Object>.Add(String, Object)

將指定的索引鍵和值加入字典。Adds the specified key and value to the dictionary.

IDictionary<String,Object>.ContainsKey(String)

判斷字典是否包含指定的索引鍵。Determines whether the dictionary contains the specified key.

IDictionary<String,Object>.Item[String]

取得或設定具有指定索引鍵的元素。Gets or sets the element that has the specified key.

IDictionary<String,Object>.Keys

取得包含 IDictionary<TKey,TValue> 之索引鍵的 ICollection<T>Gets an ICollection<T> that contains the keys of the IDictionary<TKey,TValue>.

IDictionary<String,Object>.Remove(String)

IDictionary 移除具有指定之索引鍵的項目。Removes the element that has the specified key from the IDictionary.

IDictionary<String,Object>.TryGetValue(String, Object)

取得與指定索引鍵關聯的值。Gets the value associated with the specified key.

IDictionary<String,Object>.Values

取得包含 ICollection<T> 中之值的 IDictionary<TKey,TValue>Gets an ICollection<T> that contains the values in the IDictionary<TKey,TValue>.

IDynamicMetaObjectProvider.GetMetaObject(Expression)

提供的 MetaObject 將會分派給動態虛擬方法。The provided MetaObject will dispatch to the dynamic virtual methods. 此物件可以封裝在另一個 MetaObject 內部,以提供個別動作的自訂行為。The object can be encapsulated inside another MetaObject to provide custom behavior for individual actions.

IEnumerable.GetEnumerator()

傳回逐一查看集合的列舉值。Returns an enumerator that iterates through the collection.

IEnumerable<KeyValuePair<String,Object>>.GetEnumerator()

傳回逐一查看集合的列舉值。Returns an enumerator that iterates through the collection.

INotifyPropertyChanged.PropertyChanged

當屬性值變更時發生。Occurs when a property value changes.

擴充方法

Remove<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue)

嘗試從 key 中移除具有所指定 dictionary 的值。Tries to remove the value with the specified key from the dictionary.

TryAdd<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue)

嘗試將指定的 keyvalue 新增至 dictionaryTries to add the specified key and value to the dictionary.

CopyToDataTable<T>(IEnumerable<T>)

根據輸入 DataTable 物件 (其中泛型參數 DataRowIEnumerable<T>) 傳回包含 T 物件複本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

根據輸入 DataRow 物件 (其中泛型參數 DataTableIEnumerable<T>),將 T 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

根據輸入 DataRow 物件 (其中泛型參數 DataTableIEnumerable<T>),將 T 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>)

傳回包含來源集合中每個節點祖系的項目集合。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName)

傳回包含來源集合中每個節點祖系的已篩選項目集合。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目之子代節點的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

傳回包含來源集合中每個項目和文件之子代項目的項目集合。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName)

傳回已篩選的項目集合,其中包含來源集合中每個項目和文件的子代項目。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

傳回來源集合中每個項目和文件的子項目集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName)

傳回來源集合中每個項目和文件的已篩選子項目集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中只會包含具有相符之 XName 的項目。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

傳回包含來源集合中所有節點的節點集合,依據文件順序來排序。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目的子節點集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

在來源集合中,從每一個節點的父節點移除這些節點。Removes every node in the source collection from its parent node.

適用於