C#4.0动态vs Expando ...他们在哪里适合? [英] C# 4.0 Dynamic vs Expando... where do they fit?

查看:319
本文介绍了C#4.0动态vs Expando ...他们在哪里适合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习C#4.0附带的所有新的好东西。我无法理解Dynamic和Expando类型之间的区别。从外观的东西,似乎是动态是当你想从python脚本等访问变量等.Expando似乎是一个使用ful工具,当谈到COM / Office对象。

I am trying to learn all the new goodies that come with C# 4.0. I am failing to understand the differences between the Dynamic and Expando types. From the looks of things it seems like Dynamic is when you want to access variables etc from python scripts etc.Expando seems like a use ful tool when talking with COM/Office objects. I may be incorrect here and would really love to have some input on this.

提前感谢!

推荐答案

Expando 是可在运行时添加(或删除)成员的动态类型。 dynamic 旨在允许.NET在与动态类型语言(如Python和JavaScript)接口时与类型进行交互操作。

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.

因此,如果您需要处理动态类型:use dynamic ,如果您需要处理动态数据作为XML或JSON:使用ExpandoObject

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

expando的声明显示动态和expando之间的关系:

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

dynamic expando = new ExpandoObject();

并可添加新属性:

expando.SomeNewStringVal = "Hello World!";

最后一行代码在expando对象中创建一个全新的字符串属性 SomeNewStringVal

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.

因此,expando是一种动态数据类型,可以表示动态变化的数据。简而言之。 深入了解动态和expando

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.

完整示例:

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);
    }
}

这篇关于C#4.0动态vs Expando ...他们在哪里适合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆