C# 4.0 Dynamic vs Expando… where do they fit?

為{幸葍}努か 提交于 2019-11-27 18:56:58

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!