C # dynamic learning-dynamic

Source: Internet
Author: User

Some time ago, I have been analyzing the case about dynamic, but there are only some vague concepts about dynamic and DLR. I have recently studied this part well and I am a little bit confused.

What is dynamic and what is Dynamic Language Runtime?

Dynamic means that the type check is not executed during compilation, and the object type is identified only at runtime. In this way, if you call a method or attribute that is not of the type, no error will be reported during compilation, but the error information will be captured at runtime.

Programming LanguageIt can be divided into static language and Dynamic Language. C # was originally designed as a pure static language, but to improve interoperability with dynamic languages and frameworks, finally, we decided to use the dynamic keyword to support this function.

     Public   Static   Void  M (Dynamic Arg) {dynamic result = Arg + ARG; console. writeline (Arg. GetType () + "  : " + Result );}  Static   Void Main ( String  [] ARGs ){  For ( Int I = 0 ; I < 2 ; I ++ ) {Dynamic d = (I = 0 )? 5 : (Dynamic) " Demo  "  ; M (d );}}  //  Output:  //  System. int32: 10  //  System. String: demodemo 

As shown above, different types of objects can be allocated to dynamic variables, and the object type can be determined at runtime. operations such as int type, + sum are executed, concatenates strings.
So how does the C # compiler parse the dynamic type during compilation? Let's look at the definition of method m through Il:

. Method Public Hidebysig Static   Void M ( Object Arg) cel managed {. Param [  1  ]. Custom instance  Void [System. Core] system. runtime. compilerservices. dynamicattribute:. ctor () = ( 01   00   00   00  )  //  Code size 448 (0x1c0) . Maxstack 15  . Locals Init ([  0 ]Object  Result ,[  1 ] Class [Microsoft. CSHARP] Microsoft. CSHARP. runtimebinder. csharpargumentinfo [] CS $ 0 $ 0000  ) Il_0000: NOP il_0001: lds1 _  Class [System. Core] system. runtime. compilerservices. callsite' 1 < Class [Mscorlib] system. func' 4 < Class [System. Core] system. runtime. compilerservices. callsite, Object , Object , Object > Program/ '  <M> o _ sitecontainer0  ' :: '  <> P _ Site1  '  Il_0006: brtrue. s il_0041 

Actually,CodeWhen a member is called using dynamic expressions/variables, the compiler generates special il code to describe the required operation. This special code is called payload (payload ). The dynamic type is actually parsed to the object type. In addition, the compiler adds a dynamicattribute for the property type and method parameter type, and locally defines the dynamic type inside the method, this attribute will not be added.

 

Dynamic runtime, that is, Dynamic Language Runtime (DLR). First, it achieves interoperability between dynamic languages and. NET Framework. Second, it introduces dynamic behavior into C # and Visual Basic.

C # The concept of dynamic in the language environment refers to the keywords dynamic and DLR.

 

Differences between dynamic, object and VaR

Object indicates the system. Object type, which is the root type in the C # class hierarchy. An object is usually used when the object type cannot be determined during compilation. It is often used in various interoperability scenarios. Object display conversion problems often occur:

ObjectOBJ =10; Console. writeline (obj. GetType ());IntResult = (Int) OBJ;//Int result = OBJ; error: connot implicitly convert type 'object' to 'int'

VaR is a keyword added from C #3.0. It is used to implicitly type local variables that are anonymous. When a variable is declared with the VaR keyword, the type of the variable is inferred based on the initialization string during compilation, and the type of the variable cannot be changed during runtime. Vari is often used in combination with LINQ.

 
VaRVar1 =10; Console. writeline (var1.gettype ());IntResult =Var1;//Var1 = "test"; an error occurs when you assign a string value to var1. Because the VaR type is determined, you cannot change the type. Therefore, you can only assign an integer to it.

Dynamic depends on objects to some extent, because the dynamic type uses the system. Object Type in the background. However, unlike the object, the dynamic type does not need to perform the display conversion operation during compilation. It only recognizes the type at runtime.

 
Dynamic d =10; Console. writeline (D. GetType ());//Output: system. int32IntResult =D; d="Test"; Console. writeline (D. GetType ());//Output: system. String

 

Reflection and dynamic

Sometimes we don't know the exact type of an object, but we know a method of this object. To call this method, we can use reflection:

ObjectCalc =Getcalculator (); Type calctype=Calc. GetType ();ObjectRes = calctype. invokemember ("Add", Bindingflags. invokemethod,Null,New Object[] {10,20});IntSum = convert. toint32 (RES );

Using Dynamic makes the code simpler, easier to read, and easier to understand:

 
Dynamic calc =Getcalculator ();IntSum = Calc. Add (10,20);

conclusion: dynamic can be implemented in a more concise manner. At the same time, C # also provides some dynamic classes that let us create and encapsulate our own classes, such as the dynamicobject class.

Related Article

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.