C # Programming (69) Introduction to----------DLR

Source: Internet
Author: User
Tags compact visual studio 2010

Dlr

I. In recent years, C # has always been able to squeeze the top 10 in the list of programming languages published by Tiobe Company every month, while in the last 10 years, C # has shown an overall upward trend. C # can achieve such a result, there are many factors, in which its language characteristics of the forge ahead is impressive.

The c#4 dynamic feature is part of the dynamic Language runtime (runtime, DLR). The DLR is a series of services added to the CLR that allow for the addition of dynamic languages, such as Ruby and Python, and that C # has some of the same features as these dynamic languages.

Dynamic programming languages are not new, and they have been developed using dynamic programming languages long before the object-oriented programming language became mainstream. In time, java,c#,c++ and other object-oriented programming languages thrive, in the era of the world, dynamic programming language is also in the "quiet" gongchenglvede, Occupy a considerable area of development, such as JS has become the Web client in fact the mainstream language.

In recent years, dynamic language has become very hot, such as Python,ruby.

Here's a question, why do we need to apply dynamic programming languages in development? What are the advantages of dynamic programming languages compared to C#he Java, a very mature and powerful static type programming language?

To put it simply, using dynamic programming language development has the following features:

1. Support Repl (Read-evaluate-print loop: Read-in, output, loop iteration) development model, this process is concise and clear, pointing to the core of the problem.

Case: We use ironpython[2] to become a computational 1+2+...+100, we can quickly enter a section to complete the summation of the code, and then immediately can be summed:

If using C # development looks like a lot of trouble, you have to use VS to create a project, then add a class to it, write a method in the class to complete the function of summing, in the compilation call this method of code, compile, debug, and finally get the results.

2. Easy to expand. Users can adjust the code at any time, need what function directly to the dynamic object "plus" is, not the time can be a place for them. And this modification can take effect immediately, not like C # must first modify the definition and declaration of the class, after compiling the new method to use.

In other words: Using dynamic language programming, without the "heavyweight" ooad, the entire development process is iterative quickly and never to be muddy.

3. The type resolution of a dynamic programming language is actually done at runtime, eliminating the need for many unnecessary types of conversion code, so the dynamically typed programming language tends to be more compact and less-written than statically typed programming languages.

Of course, there are drawbacks to dynamic languages:

1. Many of the errors in the code will not be discovered until run time and require specific operational environment support, are not easy to test, and do not support many of the various software engineering tools used to improve the quality of the code, and are therefore less suitable for developing applications with large scale and complex logic.

2. Programs written in dynamic languages have a low performance compared to static languages. However, with the development of computer hardware technology, such as the application of multi-core CPU, dynamic programming language and the continuous optimization of running environment, the program performance of dynamic programming language is continuously improved, in the specific application scenario, You can even approximate programs written in static languages.

Two. Embrace the c#4 of "dynamic Programming" features

In order for the C#,VB. NET programming language to have the features of a dynamic programming language, the. NET4 introduces a DLR:

The DLR runs on top of the CLR, providing a dynamic language running environment that allows programs written in dynamic languages such as Python,ruby to run on the. NET platform, while the existing. NET static type programming languages, such as C # and VB, can also take advantage of the DLR and have some characteristics of dynamic programming languages.

(1) using c#4 to write dynamic code

C#4 adds a dynamic keyword that you can use to write "Live code."

For example: The following code creates a ExpandoObject object (note must be defined as dynamic):

The namespace system.dynamic needs to be added here;

Dynamic dynamicobj = new ExpandoObject ();

The peculiarity of this object is that we can add new members to them at any time.

Dynamicobj.value = 100;//Add Field

Dynamicobj.increment = new Action (() = dynamicobj.value++);//Add method

These dynamically added members are the same as normal class member usages

for (int i = 0; i <; i++)

{

Dynamicobj.increment ();

Console.WriteLine ("Dynamicobj.value: {0}", Dynamicobj.value);

}

Analysis: The ExpandoObject object implements the Idictionary<string,object> interface, which can be seen as a Dictionary object, and all dynamically added members are elements of this Dictionary object, which means that we can not only add new members, You can also remove members that we don't need at any time.

Removing the Increment method

(Dynamicobj as Idictionary<string, object>). Remove ("Increment");

After the method has been removed, attempting to access this method will throw an runtimebinderexception exception.

(2) Simplifying code to interact with COM components using the dynamic keyword

To be in. NET this "managed world" calls the COM component in "Unmanaged world", we must use "interop assembly (Interopassembly)" As a bridge, "interop assembly" defines the correspondence between CLR type and COM type.

Just give. NET project adds a reference to the interop assembly, you can use the. NET application to create an instance of the various types contained in this assembly (that is, the COM wrapper object), the method invocation (or access to its properties) of those objects will be forwarded to the COM component.

To debug word, for example, you might often need to write code like this before c#4:

Object WordApp = new Word.Application (); Create a Word object

Object fileName = "mydoc.docx";//Specify Word Document

Object Argu = System.Reflection.Missing.Value;

Word.Document doc = WordApp. Documents.Open (ref fileName, ref ARGU,

Ref ARGU, ref ARGU, ref ARGU, ref ARGU, ref ARGU, ref ARGU,

Ref ARGU, ref ARGU, ref ARGU, ref ARGU, ref ARGU, ref ARGU,

Ref ARGU, ref Argu);

The call statement for the open () method can only be described by a "JB", because the open () method in the word component defines too many parameters.

C#4 Use the dynamic keyword, with the "named parameters and optional parameters" from the VB Secondary two new syntax features, you can write the introduction of the code.

Dynamic WordApp = new Word.Application ();

Dynamic doc = WordApp. Documents.Open (FileName: "Mydoc.docx");

The above code eliminates the need for parameters and can remove the REF keyword before the parameter.

When the above code is run, the DLR uses reflection technology to bind the dynamic expression binding (BIND) to the Word.Application proxy object contained in the COM interop assembly.

(3) C#4 Dynamic Programming Technology Insider

The dynamic variable defined in C#4 can refer to the following types of objects:

A. Traditional "Static" CLR objects

The B.Com wrapper object.

C. A "dynamic object" that implements the IDynamicMetaObjectProvider interface, ExpandoObject is an instance of this type of object.

D. Objects created by the DLR-implemented dynamic languages (such as IronRuby and IronPython)

From the C # Programmer's Point of view, all four objects are the same and can be referenced by a dynamic variable, while the DLR dynamically calls the method call and the field access request "bound" to the real object when the program runs.

The function of dynamic is supported by the DLR, which is the result of division of labor between the C # compiler and the DLR.

Take a look at the following code:

Dynamic d=100;

d++;

When the C # compiler processes the above code, it does not check that the variable D can support the self-increment operation, but instead creates a Callsite<t> object (<>p_site1) for it, declared as follows:

private static Class <main>o_sitecontainer () {

public static callsite<func<callsite,object,object>><>p_site1;

}

Chinese MSDN translates callsite<t> as a "dynamic (call) site", which is one of the core components in the DLR.

Dynamic site objects through Callsite<t>. The Create () method is created, and the C # compiler assigns it an object derived from Callsitebinder (called a "dynamic site Binding Object") as its argument.

Dynamic site-bound objects are language-specific, such as IronPython and C #, which have their own dynamic site binding objects.

The main work of a dynamic site-bound object is to convert the dynamic expression in the code (d++ in this case) to an abstract syntax tree (ast:abstract Syntax), which is called the "DLR Tree", which is the. NET 3.5 is an extension of the LINQ expression tree introduced, and is sometimes referred to as "expression tree"

The DLR internally calls the compile () method of this expression tree to generate an IL instruction, resulting in a delegate that can be executed by the CLR (in this case the type is Func<callsite, object, object>).

The dynamic Call site object (in this case, <>p__site1) has a target property that is responsible for referencing this generated delegate.

After the delegate is generated, the execution of the dynamic expression is represented as the execution of the delegate, in fact the C # compiler directly "writes dead" in the Il Code.

The simplified code is shown below (obtained by reflector, which modifies the variable name for readability):

Object d = 100;

Object cs$0$0000 = D;

if (<>p__site1 = = null)

<>p__site1 = Callsite<func<callsite, object, Object>>. Create (...);

D = <>p__site1.target (<>p__site1, cs$0$0000);

The above type inference, method binding, and IL code generation work are done at the time the program runs.

(4) is the dynamic code slow?

Dynamic programming language is easy to learn and use, code compact, development flexibility, but performance has been its "soft rib." To improve performance, the DLR has designed a three-level caching strategy.

Dynamic site Binding Object The grammar book that the dynamic invocation expression transforms into, plus the corresponding test condition (called "Test"), forms a "rule

) ", this rule can be used to determine whether a syntax tree can be used for a particular dynamic invocation expression.

Case: Observe the following dynamic expression

D1+d2

If D1 and D2 are integers of type int when the program is run, the rule generated by the DLR is:

if (d1 is int && d2 is int)//test condition

return (int) d1+ (int) D2; Syntax tree

The DLR can know whether a dynamic expression can use the syntax tree that this rule contains by examining "test conditions" in the rule.

A "rule" is the primary object of the DLR cache.

The previous dynamic site object referenced by the target property is the first-level cache, and the processing logic it implements is this:

The current processing rule, which belongs to level 1th cache

if (d1 is int && d2 is int)//test condition

return (int) d1+ (int) D2; Satisfies the test condition, returns an expression tree directly

Missing, the 2nd level, 3rd level cache is looked up, and if found, update the 1th level cache with the results found

return site. Update (SITE,D1,D2);

If no rule is hit in the level 3 cache, the call site binding object associated with this dynamic site attempts to create a new rule. If creating a new rule fails, the default call site binding object provided by the current programming language (such as C #) determines how to handle it, and the usual practice is to throw an exception.

The current version of the DLR 2nd level caches 10 rules, and the 3rd level caches 100 rules.

Since the DLR itself has designed a "rule" caching system, it takes full advantage of the JIT cache provided by the CLR (since all dynamic calling code will eventually be converted to the IL directives that the CLR can execute, and the CLR can cache the code), making dynamic code poorly performing only at the first execution. Subsequent successive invocations of its performance can approximate static code.

Three. C#4 and dynamic language inheritance

Since almost all programming languages can be represented using an abstract syntax tree, in theory the DLR supports interoperability between an infinite number of programming languages, and in the current version, interoperability between C#/VB and IronPython and IronRuby can be achieved. It is believed that the DLR implementations of other dynamic programming languages will soon appear.

An interesting place is that the current local DLR implements dynamic programming languages that begin with "Iron", such as the designers of IronRuby and Ironpython.ironpython, The DLR architect once explained at the Microsoft PDC2008 Conference that the main purpose was to avoid a python.net or pythonfor.net-like Microsoft-flavored name, IronPython. He stressed that Iron Series dynamic languages will strictly abide by the standards and norms of the dynamic language itself, respecting the historical and base classes that these dynamic languages already have, and will not introduce some limitations. NET platform, and the new language features of these languages. NET implementation to keep open source. At the same time, the author points out that the "Iron" series of languages can be well integrated with. NET existing class libraries, programming languages and tools, and can be "embedded" into. NET host programs.

(1) Dynamic Object Communication protocol

Because of the great difference between the different dynamic programming languages, it is difficult to realize the interoperability between different languages. The DLR took a smart strategy, he did not try to design a "common type System" (the CLR is doing so), but designed a "universal Object Communication Protocol", Specifies that all dynamic objects that need to interoperate must implement the IDynamicMetaObjectProvider interface, which defines a getmetaobject () method that accepts a syntax tree as a parameter to return a "dynamic metadata" object to the outside world:

Dynamicmetaobject getmetaobject (Expression parameter);

The Dynamicmetaobject object provides two important properties to the outside world, restrictions references a set of test conditions, and the expression property refers to a syntax tree. These two properties combine to be a "rule" that can be cached for a dynamic site object.

After the Dynamicmetaobject object has been obtained by the dynamic site binding object in the DLR, he invokes the various methods provided by this object to create a "rule", which is referred to by the target property of the dynamic site object (callsite<t>). Complete the work of dynamic binding.

(2) Dynamic Language integration environment

To facilitate the integration of static languages with various dynamic languages, the DLR provides a complete set of components called "Common Homestay", which includes types such as Scriptruntime,scriptscope.

We can combine static and dynamic programming languages, develop some highly interactive applications, use static programming language to build system framework, and use dynamic programming language to realize interactivity, which is a very interesting application area.

In the future, a number of static, dynamic programming languages that apply to the same library, such as the realization of the "ubiquitous reuse" goal and a step forward.

Visual Studio 2010 is new. NET programming Language F # provides specialized project templates, but does not provide support for the development of dynamic languages such as IronPython and IronRuby, and is believed to be the same with dynamic languages. NET platform, the successor version of Visual Studio directly supports the development of dynamic languages.

The path from C # 1.0~4.0 can be clearly seen in its development trajectory, and a conclusion is drawn:

The future programming language should be multi-paradigm and highly composable, and it becomes more common to combine multiple programming languages in a project or product and use multiple programming paradigms.

We can infer that the successor version of C # will go farther on this road ...

What is the DLR?

The DLR (Dynamic Language Runtime) is a Microsoft-led open source project. Provides scripting support for, net applications. The current version is 0.9, you can get the source code from CodePlex.

The DLR mainly offers the following three functions:

1. Language implementation Service provides the interoperability of the language

2. Dynamic Language runtime service provides dynamic call support

3. Public Script Host

With these modules, you can do the following things very easily

1. For your existing. NET applications, adding scripting support

2. Provide a dynamic confidant for your existing language

3. Provide dynamic operation support for any object

4. Provide the scripting language in your schema.

C # Programming (69) Introduction to----------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.