Chapter 13-dynamic Type and DLR

Source: Internet
Author: User

The content and code of this article are referenced from book Pro c#5.0 and the. NET 4.5 Framework by Apress. The intention of the writing is to review the Konwledge and gain better understanding of the. NET Framework.

1. The role of C # dynamic keyword

We learned implicit varaiable in early chapters, and once the initial assignment had been made, you have a strong typed VA Riable, any attemp to assign an imcompatible value would result in a compiler error.

    Static void implicitvariable ()        {            varnew list<int> ();            A.add (+);             " Hello " // compiler Error        }

With the release of. NET 4.0, the C # language introduced a keyword named dynamic. From a high level, you can consider the dynamic keyword a specialized form of System.Object, any value can assigned to A Dynamic Data type.

What makes a dynamic variable much different from a variable declared implicitly or via a System.Object referent was that I T is not strongly typed. The Dynamic variable can is assigned with any initial value, and can is reassigned to any new value during its lifetime.

        Static void Changedynamicdata ()        {            "hello";             false ;             New list<int> ();        }

1.1 Calling member on Dynamic Data

To invoke methods in dynamic variable, just apply the dot operator and specify a public member. However, the validity of the members of the Specify is not being checked by the compiler.

        Static void Invokememberondynamicdata ()        {            "hello";            Console.WriteLine (data. ToUpper ());             // compile file, would has runtime error        }

1.2 The role of Microsoft.CSharp.dll

When you create a new Visual Studio C # project, you'll automatically has a reference set to an assembly Microsoft.CS Harp.Dll. The most common class, Runtimebinderexception, represents an error that would be thrown if you attempt to invoke a member O n a dynamic data, which does not exist. 

        Static void Invokememberondynamicdata ()        {            "hello";             Try             {                Console.WriteLine (data. ToUpper ());                Console.WriteLine (Data.toupper ());             }             Catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) {                Console.WriteLine (ex). Message);            }        }

1.3 The scope of the dynamic keyword

The VAR keyword can never be used as a return value, a parameter, or a member of a class/structure. This isn't the case with dynamic keyword.

    class DynamicClass    {        privatestatic  dynamic Dfield;          Public dynamic Property {get;  Set;}          Public Dynamic Method () {            return1;        }    }

1.4 Limitations of the Dynamic keyword

While a great many things can is defined using the dynamic keyword, there is some limitations reagarding its usage.  The Dynamic Data item can not be the use of lambda expression or C # anonymous methods when calling a methods. In addition, it had very limited use within LINQ to Objects and other LINQ technologies.

1.5 Practise use of the dynamic keyword

In a few circumstances, the dynamic keyword can radically reduce the amount of code you need to write. Specifically, if you are building. NET applications, then make heavy use of late binding. As well, if is building a. NET application that needs to communicate with legacy COM Library.

The use of dynamic keyword is a trade-off between brevity of code, and type safety.

2. The role of the Dynamic Language Runtime (DLR)

With the release. NET 4.0, the Common Language Runtime (CLR) is supplemented with a complementary Runtime environment Nam Ed the Dynamic Language Runtime (DLR). In a nutshell, a dynamic runtime allows a dynamic language the ability to discover types completely at runtime with no COM Pile-time checks.

2.1 The role of expression trees

The DLR makes use of expression trees to capture the meaning of a dynamic call in neutral terms.

2.2 The role of System.dynamic namespace

The system. Core.dll assembly includes a namespace named System.dynamic. You'll only have the use of the namespace if you want to build a custom runtime builder.

2.3 Dynamic Runtime lookup of expression trees

If The Dynamic Data type is pointing in memory to a COM object, the expression tree was sent to a low-level COM interface n Amed IDispatch.

If The Dynamic data is not pointing to a COM object, the expression tree could be passed to an object implementing the Idyna Micobject interface. This interface was used behind the scenes to allow language such as IronRuby, to take expression tree and map it to Ruby SP Ecifies.

If The dynamic data is pointing to a normal C # object, the expression tree is dispatched to C # runtime binder.

After the expression tree have been processed by a given binder, the dynamic data would be resolved to the real in-memory da TA type.

2.4 Late bind calls using dynamic types

//normal procedures of late binding using reflection        Static voidlatebinding (Assembly asm) {Try{Type car= asm. GetType ("Carlibrary.car"); ObjectMyCar =activator.createinstance (CAR); MethodInfo Method= car. GetMethod ("Print"); Method. Invoke (MyCar,NULL); }            Catch(Exception ex) {Console.WriteLine (ex).            Message); }        }
 // using dynamic  static  void   latebinding (Assembly ASM) {  try  {Type car  = asm. GetType ( carlibrary.car   " );                Dynamic MyCar  = Activator.CreateInstance (car);            Mycar.print ();                 catch   (Exception ex) { Console.WriteLine (ex.            Message); }        }

By declaring the MyCar using dynamic, the heavy lifting of reflection are done using DRL.

Chapter 13-dynamic Type and DLR

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.