dynamic详解

简介: 一、简介 在通过 dynamic 类型实现的操作中,该类型的作用是绕过编译时类型检查, 改为在运行时解析这些操作。 dynamic 类型简化了对 COM API(例如 Office Automation API)、动态 API(例如 IronPython 库)和 HTML 文档对象模型 (DOM) 的访问。

一、简介

在通过 dynamic 类型实现的操作中,该类型的作用是绕过编译时类型检查, 改为在运行时解析这些操作。 dynamic 类型简化了对 COM API(例如 Office Automation API)、动态 API(例如 IronPython 库)和 HTML 文档对象模型 (DOM) 的访问。

在大多数情况下,dynamic 类型与 object 类型的行为是一样的。 但是,不会用编译器对包含 dynamic 类型表达式的操作进行解析或类型检查。 编译器将有关该操作信息打包在一起,并且该信息以后用于计算运行时操作。 在此过程中,类型 dynamic 的变量会编译到类型 object 的变量中。 因此,类型 dynamic 只在编译时存在,在运行时则不存在。

以下示例将类型为 dynamic 的变量与类型为 object 的变量对比。 若要在编译时验证每个变量的类型,请将鼠标指针放在 WriteLine 语句中的dyn 或 obj 上。 IntelliSense 显示了 dyn 的“动态”和 obj 的“对象”。

dynamic 关键字可以直接出现或作为构造类型的组件在下列情况中出现:

  • 在声明中,作为属性、字段、索引器、参数、返回值或类型约束的类型。 下面的类定义在几个不同的声明中使用 dynamic

   class ExampleClass
    { 
        static dynamic field; 
        dynamic prop { get; set; } 
        public dynamic exampleMethod(dynamic d)
        {
            dynamic local = "Local variable";
            int two = 2;
            if (d is int)
                return local;
            else
                return two;
        }
    }

 

  • 在显式类型转换中,作为转换的目标类型。
static void convertToDynamic()
        {
            dynamic d;
            int i = 20;
            d = (dynamic)i;
            Console.WriteLine(d);

            string s = "Example string.";
            d = (dynamic)s;
            Console.WriteLine(d);

            DateTime dt = DateTime.Today;
            d = (dynamic)dt;
            Console.WriteLine(d);

        }
        // Results:
        // 20
        // Example string.
        // 2/17/2009 9:12:00 AM

 

  • 在以类型充当值(如 is 运算符或 as 运算符右侧)或者作为 typeof 的参数成为构造类型的一部分的任何上下文中。 例如,可以在下列表达式中使用 dynamic

 

            int i = 8;
            dynamic d;
            // With the is operator.
            // The dynamic type behaves like object. The following
            // expression returns true unless someVar has the value null.
            if (someVar is dynamic) { }

            // With the as operator.
            d = i as dynamic;

            // With typeof, as part of a constructed type.
            Console.WriteLine(typeof(List<dynamic>));

            // The following statement causes a compiler error.
            //Console.WriteLine(typeof(dynamic));

 

二、使用

 

作为返回值

public void Main()
    {
        dynamic data =Get();
        //调用 data.a   data.b  data.c
    }
 
    public dynamic Get()
    {  
        return new { a = 'a', b = 1, c = 1.1 };
    }

 

三、应用

1、自动反射

2、COM组件互操作

3、混合编程,例如IronRuby和IronPython

4、处理Html DOM对象

5、还有一种应用,数据传输中格式转换,如:对象转json等,很方便

 

相关文章
|
1月前
|
人工智能 安全 机器人
【C++】dynamic_cast基本用法(详细讲解)
【C++】dynamic_cast基本用法(详细讲解)
|
10月前
C#-数据类型(dynamic)
C#-数据类型(dynamic)
48 0
|
SQL 流计算
Introduction to Dynamic Tables
The concept of dynamic tables is analogous to the materialized view in a database. Similar to static batch tables, dynamic tables enable Structured Qu
1605 0