Dynamic primitive type

Source: Internet
Author: User

C#编译器允许将一个表达式的类型标记为dynamic。还可以将一个表达式的结果放到一个变量中,并将变量的类型标记为dynamic。

代码使用dynamic表达式/变量来调用一个成员是,编译器会生成特殊的IL代码来描述所需的操作。这种特殊的代码称为payload(有效载荷)。在运行时,payload代码根据当前由dynamic表达式/变量引用的对象的实际类型来决定具体执行的操作。

有时候三元运算符会遇到前后类型不一致的情况。

以下代码使用dynamic进行了演示。

using System;namespace dynamic{    internal static class DynamicDemo    {        public static void Main()        {            for (Int32 demo = 0; demo < 2; demo++)            {                dynamic arg = (demo == 0) ? (dynamic)5 : (dynamic)"A";                M(arg);            }        }        private static void M(Int32 n)        {            Console.WriteLine("M(Int32):" + n);        }        private static void M(String s)        {            Console.WriteLine("M(String):" + s);        }    }}

执行Main时,会得到以下输出:

正常情况下,编译器不允许写代码将一个表达式从Object隐式转型为其他类型,必须使用显示转型。然而,编译器允许使用隐式转型语法将一个表达式从dynamic转型为其他类型:

Object o1 = 123;Int32 n1 = o1;//ErrorInt32 n2 = (Int32)0;//Okdynamic d1 = 123;Int32 n3 = d1;//Ok

从dynamic转型为其他类型时,虽然编译器允许省略显示转型,但CLR会在运行时验证转型,确保类型安全性得以保持。如果对象的类型不兼容于要转换成的类型,CLR会抛出一个InvalidCastException异常。

 

dynamic基元类型

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.