C #4.0 new features (I) dynamic search
Under the leadership of the great god Anders, the C # language is evolving more and more quickly towards the first artifact in the programming language universe. The new features of C #4.0 are centered on "dynamic" (dynamic) in this article, we will first look at the first new feature: Dynamic lookup ).
1. First knowledge of dynamic
Dynamic search allows you to dynamically bind operations on an object to the object type at runtime, regardless of whether the object is reflected by COM, ironpython, HTML Dom, or CLR. You can bypass the type check of the compiler in the program, and discard the type matching (lookup) to the runtime. If you need to operate such an object, a brand new type will be used:Dynamic
Dynamic is a type that is different from that supported by all CTS, because it is not an object! Specifically, it will tell the compiler that "Please do not treat me as any object for the time being !". It seems that this is similar to the past reflection, but dynamic allows usDirectTo perform operations on this unknown object, we will use an example to illustrate the convenience of dynamic. I installed a download software named X ray on my computer, which provides some COM components for calling. In the past, I needed to call this COM object like this:
Without Dynamic
Private Static void nodynamiccall (string url = "http://www.sunhao.cc/temp/lgxz.wma ")
{
Type thunderagent;
Object objthunderagent;
Object [] parameter = new object [14];
If (URL! = NULL & URL. length> 0)
{
Thunderagent = type. gettypefromprogid ("thunderagent. Agent ");
Objthunderagent = activator. createinstance (thunderagent );
Parameter [0] = URL; // URL
Parameter [1] = "";
Parameter [2] = "";
Parameter [3] = "";
Parameter [4] = URL; // ref URL
Parameter [5] =-1;
Parameter [6] = 0;
Parameter [7] =-1; // threadcount
Parameter [8] = ""; // strcookie
Parameter [9] = "";
Parameter [10] = "";
Parameter [11] = 1;
Parameter [12] = "";
Parameter [13] =-1;
Thunderagent. invokemember ("addtask5", bindingflags. invokemethod, null, objthunderagent, parameter );
Object [] parm = new object [1] {1 };
Thunderagent. invokemember ("committasks2", bindingflags. invokemethod, null, objthunderagent, parm );
}
}
This method called through type. invokememer on the COM object is awkward and helpless, because the compiler must first bind the type of the method caller. However, with the dynamic type, we can operate the above COM object in this way:
With dynamic
Type agenttype;
If (URL! = NULL & URL. length> 0)
{
Agenttype = type. gettypefromprogid ("thunderagent. Agent ");
Dynamic dagent = activator. createinstance (agenttype );
Dagent. addtask5 (URL, "", URL,-1, 0,-1, "", 1 ,"", -1 );
Dagent. committasks2 (1 );
}
The direct call method is more natural. However, you may ask, since the dagent type here is unknown, and its addtask5 method does not know its existence at compilation, isn't any legal or illegal call subject to the supervision of the compiler, and leave all possible dangers to the runtime? Indeed, the compiler only checks calls of various types supported by CTS, while dynamic is not mapped to any type of CTS at the time of compilation.
Tips The dynamic mentioned above is not an object sentence. If it is correct only before the program runs, dynamic will be declared as an object at runtime, the following is the information on the stack for allocating local parameters described by IL:
Dynamic Il
. Method private hidebysig static void dynamiccall ([opt] string URL) cel managed
{
. Param [1] = "http://www.sunhao.cc/temp/lgxz.wma"
// Code size 420 (0x1a4)
. Maxstack 17
. Locals Init ([0] class [mscorlib] system. Type agenttype,
[1]
Object
Dagent,
[2] bool CS $4 $0000,
[3] class [microsoft. CSHARP] Microsoft. CSHARP. runtimebinder. csharpargumentinfo [] CS $0 $0001)
// N rows are omitted below
The compiler is powerless on any operation that occurs on the dynamic type. The only job it can do is to collect information about the dynamic object for the runtime, such as the method signature above. Dynamic provides the convenience of accessing COM objects, but because it destroys the strong type of C # To a certain extent, it also requires programmers to be fully responsible for the code they write, increase the debug cost. Therefore, dynamic is risky and therefore requires caution.
2. DLR and custom dynamic types
Dynamic Language Runtime is a new set of APIs in. Net 4.0. For C #, DLR provides Microsoft. CSHARP. runtimebinder namespace [1], which provides powerful runtime interoperability (such as COM and ironpython) capabilities for C #. DLR also has an excellent caching mechanism. Once an object is successfully bound, in the next call, CLR can directly operate on objects of the specified type, instead of using DLR to lookup. If you want to implement a dynamic object in your code, you can inherit the dynamicobject [2] class and implement several get and set methods. The following is a simple example:
Myclass
Public class myclass: dynamicobject
{
Public override bool tryinvokemember (invokememberbinder binder, object [] ARGs, out object result)
{
Result = binder. Name;
Return true;
}
}
The above Code directly returns the name of a method when trying to invoke a method. The following code outputs the Method Name:
Code
Dynamic d = new myclass ();
Console. writeline (D. anymember ());
3. Use of dynamic
Dynamic itself is also a type (although only the compiler knows it and does not know it at runtime), and dynamic implements implicit and explicit operators, in theory, dynamic can be used for any type that can use CLR. The following code is valid:
Dynamic use case
Dynamic d = (dynamic) 2;
Action <dynamic> dact = new action <dynamic> (dynamic n) => {console. Write (N. GetType () + ":" + n );});
Dact (d );
However, dynamic is not omnipotent:
1). Currently, dynamic search does not support calling extension methods (it may be supported in future C # versions ).
2) The anonymous method and Lambda expression cannot be converted to dynamic, that is, dynamic d = x => X; is invalid. In fact, lambda expressions cannot be converted to objects. The same is true because a Lambda expression is either interpreted as a delegate type by the compiler or as an expression tree in the context. However, if the context lacks type information, the compiler will remove it.
4. Summary
Dynamic is the core feature of C #4.0. It seems that a strong language like C # has some Dynamic Language Features and is a perfect combination of C # And. net. As mentioned at the beginning of this article, as a programming language, C # is practicing the spirit of the North and the dark [3]. In this way, C # may become a necessary weapon for home-based travel to kill people.
5. Reference
Http://msdn.microsoft.com/en-us/library/microsoft.csharp.runtimebinder (vs.100). aspx
[2] http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject (vs.100). aspx
[3] http://baike.baidu.com/view/146278.htm
Author: freesc Huang @ cnblogs