`

c# - Dynamic and ExpandoObject

c# 
阅读更多

ExpandoObject as we have introduce in the  "C# - DynamicObject with Dynamic and create wrapper with DynamicObject " section in that it allows dynamically add/remove properties. and in tihs post, we will going to examine the attributes of ExpandoObject more closely.

In general, ExpandoObject supports dynamic binding, which enables you to use Standard syntax such as sampleObject.sampleMember instead of more complext syntax like sampleObjects.GetAttribute("sampleMember");

You have to create instance of ExpandoObject with dynamic keyword. 

you can do the following with an expandoObject. 

  • Add new Members
  • Add method (in the form of delegate) 
  • Adding Events.(this is super cool)
  • passing as Parameter (dynamic as the sole type of the parameter) 
  • Enumeraing and Deleting Members
  • Receiving notification of property Changes. 

Below is the code to show various aspect of ExpandoObject, and you may find more information on the Expando from the MSDN introduction .


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;

namespace ExpandoObjectDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            dynamic sampleObject = new ExpandoObject();
            
            // Adding new members
            sampleObject.test = "Dynamic Property";
            Console.WriteLine(sampleObject.test);
            Console.WriteLine(sampleObject.test.GetType());

            //adding complex data member (data types other than primitive types such as string)
            sampleObject.number = 10;
            sampleObject.Increment = (Action) (() => { sampleObject.number++; });
            Console.WriteLine(sampleObject.number);
            sampleObject.Increment();
            // After calling the Increment methods.
            Console.WriteLine(sampleObject.number);

            // Add an event to an instance of the ExpandoObject class
            sampleObject.sampleEvent = null; // the chanllenge of event is that you cannot specify the type of the Event when you declare it 
            sampleObject.sampleEvent += new EventHandler(SampleHandler); // how does it knows that sampleEvent is an Event? -- I Guess this must be late bound and the place holding sampleEvent might change depending on the context
            sampleObject.sampleEvent(sampleObject, new EventArgs());

            // Passing Parameter
            dynamic employee, manager;
            employee = new ExpandoObject();
            employee.Name = "John Smith";
            employee.Age = 33;

            manager = new ExpandoObject();
            manager.Name = "Allison Brown";
            manager.Age = 42;
            manager.TeamSize = 10;
            
            WritePerson(manager);
            WritePerson(employee);


            // Enumeraing and deleting members
            // you can cast the ExpandoObject to an instance of IDictionary<string, object>
            foreach (var property in (IDictionary<string, Object>) employee)
            {
                var key = property.Key;
                var value = property.Value;
                Console.WriteLine(key + ":" + value);
            }

            // also, you can remove items after casting back to IDictionary<string, object>
            ((IDictionary<string, object>) employee).Remove("Name");

            // you can receive notification on property changes
            ((INotifyPropertyChanged) employee).PropertyChanged += new PropertyChangedEventHandler(HandlePropertyChanges);
            employee.Name = "John Smith";
        }

        static  void SampleHandler(object sender, EventArgs e)
        {
            Console.WriteLine("SampleHandler for {0} event", sender);
        }

        // show passing as parameters
        private static void WritePerson(dynamic person)
        {
            Console.WriteLine("{0} is {1} years old.", person.Name, person.Age);

            try
            {
                // the following shall cause an exception , if object passed in is a Person object
                Console.WriteLine("Manager {0} people", person.TeamSize);
            }
            catch
            {
                // Ignore
            }

        }

        private static void HandlePropertyChanges(object sender, PropertyChangedEventArgs e)
        {
            Console.WriteLine("{0} has changed. ", e.PropertyName);
        }
    }
}

 if you want to find some references , here it is

 

ExpandoObject class

 

 

分享到:
评论

相关推荐

    C# Dynamic之:ExpandoObject,DynamicObject,DynamicMetaOb的应用(下)

    C#中的动态对象是通过DynamicObject和ExpandoObject类来实现的,这两个类都是.NET框架4.0引入的,用于支持动态编程。动态编程允许在运行时创建和修改对象的行为,这在某些场景下非常有用,比如与动态语言交互或者在...

    C# Dynamic之:ExpandoObject,DynamicObject,DynamicMetaOb的应用(上)

    在C#编程语言中,动态类型(Dynamic)提供了一种在运行时创建和操作对象的新方式,使得开发者能够在不完全了解对象结构的情况下进行交互。本文将深入探讨三个与动态类型相关的关键概念:ExpandoObject、...

    ef6-dynamic-dbset:示例代码,演示在Entity Framework 6中在运行时创建实体集和具体类

    在C#中,动态编程主要通过`dynamic`关键字实现,它可以让我们在编译时不指定类型,而在运行时确定类型。动态DbSet的实现可能涉及到以下步骤: 1. **创建动态实体类**:首先,我们需要能够在运行时创建具有动态属性...

    C#4.0引入了一个新的关键字dynamic,用来表示动态类型 dynamic的出现让C#具有了弱语言类型的特性

    使用 C# 4.0 中的 dynamic 关键字,可以编写“动态”的代码,例如创建一个 ExpandoObject 对象,可以随时给它增加新成员。 使用 C# 4.0 中的 dynamic 关键字,可以简化与 COM 组件交互的代码。以前,在 C# 中调用 ...

    C#中的动态类型(Dynamic)的项目工程

    在C#编程语言中,动态类型(Dynamic)是一种强大的特性,它允许程序员在运行时进行类型检查和操作。这个特性引入自C# 4.0版本,为开发者提供了更大的灵活性,尤其是在处理非强类型的数据或者与动态语言如Python、...

    c#中使用动态类的样例程序

    C# 4.0引入了`dynamic`关键字,它允许我们在编译时不进行任何类型检查,而是在运行时进行所有的类型检查和绑定。这使得能够编写更灵活的代码,尤其是在与非C#组件交互时,如JavaScript库、IronPython等。 2. **...

    深入C# 4.0 新特性dynamic、可选参数、命名参数的详细介绍

    现在这个js动态语言的特性,我们也可以在c#中使用了,前提是将一个变量声明为ExpandoObject类型。如下例: 代码如下:static void Main(string[] args) { dynamic t = new ExpandoObject(); t.Abc = “abc”; t....

    C#的动态调用方法[归类].pdf

    本文将深入探讨C#中的动态调用方法,主要包括动态类型dynamic的使用以及与反射的对比,以及ExpandoObject类和自定义动态类扩展的应用。 首先,让我们回顾一下动态类型dynamic的基本用法。在传统的静态类型(如int、...

    C#探秘系列(四)——GetHashCode,ExpandoObject

    在C#编程中,`GetHashCode` 和 `ExpandoObject` 是两个非常有趣且实用的概念。本文将深入探讨这两个主题。 首先,让我们来看看 `GetHashCode`。`GetHashCode` 是.NET框架中每个对象实例都具有的一个方法,它返回一...

    C# 本质论 第5版 C# 6.0

    dynamic obj = new System.Dynamic.ExpandoObject(); obj.Name = "John"; Console.WriteLine(obj.Name); ``` 9. **迭代器块**(Iterator Blocks):允许在yield返回的上下文中使用迭代器,使得枚举器的实现更加...

    CLR via C# 3rd Edition

    增加了对checked和unchecked代码、BigInterger类型以及C# 4.0 dynamic类型的讨论。 Chapter 6-Type and Member Basics 无新话题。 Chapter 7-Constants and Fields 无新话题。 Chapter 8-Methods 新增了扩展...

    DynamicJson

    dynamic dynObj = new ExpandoObject(); dynObj.name = "John"; dynObj.age = 30; string json = JsonConvert.SerializeObject(dynObj); Console.WriteLine(json); // 输出 "{\"name\":\"John\",\"age\":30}" ``` 四...

    Programming C# 4.0 6th.Edition

    dynamic obj = new ExpandoObject(); obj.Name = "John Doe"; Console.WriteLine(obj.Name); ``` - **并行LINQ示例**:利用PLINQ,可以轻松地对大数据集进行高效的并行处理。 ```csharp var numbers = ...

    C#动态填充toolscrip

    - 在C#中,我们可以通过`ExpandoObject`类来创建动态属性。这个类实现了`IDynamicMetaObjectProvider`接口,使得可以在运行时添加、删除或修改对象的属性。 - 事件处理则可以通过`+=`运算符来动态添加事件处理程序...

    C#4.0新特性介绍

    - **动态语言运行时**:C#4.0提供了一套用于处理动态类型的新API,包括`System.Dynamic`命名空间中的类,如`ExpandoObject`,这是一个动态对象,可以在运行时动态扩展其属性和方法。 - **已知问题**:动态查找虽然...

    C#在运行时动态创建类型的实现方法

    在C#编程中,动态类型创建是在运行时创建新的类型实例的能力,这使得代码更加灵活,能够适应不可预知的数据需求或实现特定的高级功能。本文将深入探讨如何使用C#在运行时动态创建类型,主要通过动态生成C#源代码并...

    C#编写上位机使用UDP给单片机发送Json格式数据

    dynamic data = new ExpandoObject(); data.Message = "Hello, Microcontroller!"; data.Value1 = 42; string jsonString = JsonConvert.SerializeObject(data); // 如果使用Newtonsoft.Json ``` 或者使用...

Global site tag (gtag.js) - Google Analytics