由於我寫了你指的MSDN文章,我想我必須回答這個問題。
首先,我預料到了這個問題,這就是爲什麼我寫了一篇博客文章,顯示ExpandoObject的實際用例:Dynamic in C# 4.0: Introducing the ExpandoObject。
稍後,ExpandoObject可以幫助您創建複雜的分層對象。例如,假設你在字典中有字典:
Dictionary<String, object> dict = new Dictionary<string, object>();
Dictionary<String, object> address = new Dictionary<string,object>();
dict["Address"] = address;
address["State"] = "WA";
Console.WriteLine(((Dictionary<string,object>)dict["Address"])["State"]);
層次越深,醜陋的是代碼。藉助ExpandoObject,它保持優雅和可讀性。
dynamic expando = new ExpandoObject();
expando.Address = new ExpandoObject();
expando.Address.State = "WA";
Console.WriteLine(expando.Address.State);
其次,因爲它已經指出,ExpandoObject實現INotifyPropertyChanged接口,讓您以比一本字典屬性的更多控制。
最後,您可以添加事件ExpandoObject喜歡這裏:
class Program
{
static void Main(string[] args)
{
dynamic d = new ExpandoObject();
// Initialize the event to null (meaning no handlers)
d.MyEvent = null;
// Add some handlers
d.MyEvent += new EventHandler(OnMyEvent);
d.MyEvent += new EventHandler(OnMyEvent2);
// Fire the event
EventHandler e = d.MyEvent;
if (e != null)
{
e(d, new EventArgs());
}
// We could also fire it with...
// d.MyEvent(d, new EventArgs());
// ...if we knew for sure that the event is non-null.
}
static void OnMyEvent(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent fired by: {0}", sender);
}
static void OnMyEvent2(object sender, EventArgs e)
{
Console.WriteLine("OnMyEvent2 fired by: {0}", sender);
}
}
有趣。感謝您的信息:事件。對我來說這是一個新的。 – 2009-11-02 19:11:18
@ Reed 是的,事件尚未記錄在ExpandoObject中。這個特殊的例子實際上出現在博客的討論中。我可能稍後將它添加到文檔中。 – 2009-11-02 19:16:53
@AlexandraRusina,當你說'd.MyEvent = null;'時,它是如何知道這是一個事件?或者它不? – Shimmy 2012-02-06 22:49:32