问题描述
我正在努力学习 C# 4.0 带来的所有新东西.我无法理解 DynamicObject
和 ExpandoObject
类型之间的区别.似乎使用了 DynamicObject
,例如当您想在与 COM/Office 对象交谈时从 Python 脚本和 ExpandoObject
访问变量时.我对吗?它们的用途有什么区别?
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?
推荐答案
Expando 是一种 dynamic
类型,可以在运行时向其中添加(或删除)成员.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.
因此,如果您需要处理动态类型:使用 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();
以及添加新属性的能力:
And the ability to add a new property:
expando.SomeNewStringVal = "Hello World!";
最后一行代码在名为 SomeNewStringVal
的 expando 对象中创建了一个全新的字符串属性.字符串类型是从赋值中推断出来的.
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 是一种动态数据类型,可以表示动态变化的数据.简而言之就是这样.此处深入了解动态和扩展.
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 Dynamic vs Expando ...它们适合在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!