Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# 4.0 - C# 4.0 Dynamic vs Expando... where do they fit?

I am trying to learn all the new goodies that come with C# 4.0. I am failing to understand the differences between the DynamicObject and ExpandoObject types. It seems like DynamicObject is used e.g. when you want to access variables from Python scripts and ExpandoObject when talking with COM/Office objects. Am I right? What is the difference in their use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Expando is a dynamic type to which members can be added (or removed) at runtime. dynamic is designed to allow .NET to interoperate with types when interfacing with dynamic typing languages such as Python and JavaScript.

So, if you need to handle a dynamic type: use dynamic and if you need to handle dynamic data such as XML or JSON: use ExpandoObject

The declaration of an expando shows the relationship between dynamic and the expando:

dynamic expando = new ExpandoObject();

And the ability to add a new property:

expando.SomeNewStringVal = "Hello World!";

That last line of code creates a brand new string property in the expando object called SomeNewStringVal. The string type is inferred from the assignment.

So an expando is a dynamic data type that can represent dynamically changing data. That's it in a nutshell. Here's a deeper look at dynamic and expando.

Complete example:

using System;
using System.Dynamic;

class Program
{
    static void Main(string[] args)
    {
        dynamic expando = new ExpandoObject();
        expando.SomeNewStringVal = "Hello Brave New Whirrled!";
        Console.WriteLine(expando.SomeNewStringVal);

        // more expando coolness/weirdness:
        var p = expando as IDictionary<String, object>;
        p["A"] = "New val 1";
        p["B"] = "New val 2";

        Console.WriteLine(expando.A);
        Console.WriteLine(expando.B);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...