C # Programming Summary (14) dynamic

Source: Internet
Author: User

C # Programming Summary (14) Dynamic Introduction

Visual C # 2010 introduces a new typeDynamicThe type is a static type, but the type isThe dynamic object skips static type checking.In most cases, the object is like a typelike object. at compile time, the element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to consider whether an object is getting its own value from a COM API, from a dynamic language (such as IronPython), from the HTML Document Object Model (DOM), from reflection, or from another location in the program. However, if the code is not valid, the error is caught at run time.

var vs. dynamic

1. var is replaced with the actual type at compile time, and dynamic is actually type object.

Once compiled, the compilation period automatically matches the actual type of the VAR variable and replaces the declaration of the variable with the actual type, which looks as if we were using the actual type to declare when we coded it. When dynamic is compiled, it is actually an object type, except that the compiler makes special processing of the dynamic type so that it does not perform any type checking during compilation, but instead puts type checking into the runtime.

2, intelligent perception.

Variables declared with VAR support IntelliSense because visual Studion can infer the actual type of the Var type, whereas a variable declared with dynamic does not support IntelliSense because the compiler knows nothing about the type of its run time. Using IntelliSense for dynamic variables prompts that this operation will resolve at run time.

Simple case

Write a test program for Hello World, define the Dynamictest type, and add the Welcome method, whose parameter is name.

Then create a dynamic object and call the Welcome method. parameter is empty.

Using System;namespace dynamicsample{    class program    {        static void Main (string[] args)        {            dynamic obj = new Dynamictest ();            Obj. Welcome ();        }    }    Class Dynamictest    {public        void Welcome (string name)        {            Console.WriteLine ("Hello {0},welcome to Dynamic world. ", name);}}}    

See what's going on, through the tests found:

The compilation passed without any exception.

Run-time throws exception, exception information:

Unhandled Microsoft.CSharp.RuntimeBinder.RuntimeBinderException hresult=-2146233088 message= "Welcome" method is not overloaded with "0" parameters       source=anonymously Hosted dynamicmethods Assembly StackTrace: In Callsite.target (Closure, CallSite, Object) At System.dynamic.updatedelegates.updateandexecutevoid1[t0] (CallSite site, T0 arg0) in DynamicSample.Program.Main (Str ing[] args) location E:\donet\c#\dynamicsample\dynamicsample\program.cs: line number 13 at system.appdomain._nexecuteassembly (Runtime  Assembly Assembly, string[] args) in System.AppDomain.ExecuteAssembly (String assemblyfile, Evidence assemblysecurity, String[] args) in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () in System.Threading.Executi Oncontext.runinternal (ExecutionContext ExecutionContext, ContextCallback callback, Object State, Boolean PRESERVESYNCCTX) in System.Threading.ExecutionContext.Run (ExecutionContext executioncontext, ContextCallback Callbac K, Object State, Boolean preservesyncctx) in SYstem. Threading.ExecutionContext.Run (ExecutionContext ExecutionContext, ContextCallback callback, Object State) in system.t Hreading.  Threadhelper.threadstart () InnerException:

After correction:

    Class program    {        static void Main (string[] args)        {            Dynamic obj = new Dynamictest ();            String name = "Tom";            Obj. Welcome (name);            Console.WriteLine ("Input any key to exit.");            Console.readkey ();        }    }

Operation Result:

If you change to Var, define the object, and call the method, the code below, the compiler will error:

            var v1 = new Dynamictest ();            V1. Welcome ();

Error message:

    Error    CS7036    does not provide an argument corresponding to the required parameter "name" for "Dynamictest.welcome"    dynamicsample    Program.cs    15    Error    CS7036    There is no argument given, corresponds to the required formal parameter ' name ' of ' Dynamictest.welcome (str ing) '    dynamicsample    

Dynamic Application Range

1. In a declaration, you can use dynamic as a type of property, field, indexer, parameter, return value, or type constraint.

2, in an explicit type conversion, as the target type of the transformation. Any object can be implicitly converted to dynamic.

3, in any context where the type acts as a value (such as the is operator or as operator to the right) or as a parameter of typeof as part of a constructed type.

An example is given to specify:

    Class Dynamicuser {//<summary>//////</summary> public dynamic User        Id        <summary>///Properties///</summary> public dynamic UserName {get; set;} <summary>///Play games///(dynamic can be used as parameters, return values, etc.)///</summary>//<param name= "            Game "></param>///<returns></returns> public dynamic Play (dynamic game) {            Dynamic Defaultgame = "Play Basketball.";            Dynamic Secgame = "Play with mud.";            if (game is int) {return defaultgame;            } else {return secgame; }}////<summary>//////</summary> public void converttodynamic (ob            Ject obj) {dynamic D;            D = (dynamic) obj;        Console.WriteLine (d); }//<summary>///Type determination///(dynamic can use is, as, typeof)//</summary> public void Typecheck ()            {int age = 20; Console.WriteLine ("Age is Dynamic?")            {0} ", age is dynamic);            Dynamic d = age as dynamic;                                    Console.WriteLine ("Age:{0}", D);        Console.WriteLine ("List<dynamic> ' s type is {0}", typeof (List<dynamic>)); }    }

Test Case:

            Dynamicuser user = new Dynamicuser ();            User.userid = 123;            User. UserName = "Lucy";            User. Converttodynamic (User.userid);            User. Converttodynamic (user. UserName);            User. Typecheck ();            Console.WriteLine ("Input any key to exit.");            Console.readkey ();

Test results:

The execution efficiency of dynamic

On the efficiency of the dynamic issue, here is not open, follow-up specifically to discuss ...

Application

1. Automatic reflection

2. COM Component Interoperability

3, mixed programming, such as IronRuby and IronPython

4. Working with HTML DOM objects

5, there is an application, data transmission format conversion, such as: object to JSON, etc., very convenient

C # Programming Summary (14) 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.