Correct usage of dynamic keywords in C # (recommended) _c# tutorial

Source: Internet
Author: User
Tags datetime new set reflection

Dynamic is a new feature of FrameWork4.0. The presence of dynamic makes C # an attribute of a weak language type. The compiler no longer checks the type at compile time, and the default dynamic object at compile time supports any features you want. For example, even if you know nothing about the objects returned by the Getdynamicobject method, you can invoke the code as follows, and the compiler will not complain:

Dynamic DynamicObject = Getdynamicobject ();
Console.WriteLine (dynamicobject.name);
Console.WriteLine (Dynamicobject.samplemethod ());

When it comes to proper usage, you should first point out an error usage:

Often someone will take the keyword of Var to compare with dynamic. In fact, var and dynamic are completely two concepts and should not be compared at all. var is actually the "syntactic sugar" that is thrown at the compile time, and once compiled, the compile period automatically matches the actual type of the VAR variable and replaces the variable's declaration with the actual type, which looks as if we were using the actual type when we were coding. When dynamic is compiled, it is actually an object type, except that the compiler makes special handling of the dynamic type so that it does not perform any type checking during compilation, but instead puts the type check in the runtime.

This can be seen from the Visual Studio Editor window. Variables declared with VAR support IntelliSense because visual Studion can infer the actual type of the Var type, while variables declared with dynamic do not support IntelliSense because the compiler knows nothing about the type of its runtime. Using IntelliSense for dynamic variables prompts "This action will be resolved at run time."

The point that the dynamic variable is an object variable can be validated by the IL code, where the IL code is no longer posted. Of course, the compiler also handles dynamic declarations to distinguish between direct object variables.

Dynamic is being made up by MSDN for ease of interoperability, and I feel it is based on this that some developers misunderstand that because many developers do not touch code such as COM + or office two development, there is a compelling need for a dynamic application reason. So, in daily development, I think dynamic is a valuable point:

Type conversions

Conversions between instances of dynamic types and instances of other types are simple and developers can easily switch between dyanmic and non dynamic behavior. Any instance can be implicitly converted to an instance of dynamic type, as shown in the following example:

Dynamic D1 = 7;
Dynamic D2 = "a string";
Dynamic d3 = System.DateTime.Today;
Dynamic D4 = System.Diagnostics.Process.GetProcesses ();
Conversely, an implicit conversion can is dynamically applied to any expression of type dynamic.

Conversely, any expression of type dynamic can also be implicitly convertible to another type.

int i = d1;
string str = d2;
DateTime dt = D3;
system.diagnostics.process[] procs = D4;

Overload problem with dynamic type parameters in method

If a method is invoked to pass an object of dynamic type, or if the object being invoked is a dynamic type, then the overload is judged to occur at run time, not at compile times.

Dynamic Language runtime (Dynamics Language runtime DLR)

The dynamic language runtime is a new set of APIs in the. NET Framework 4 Beta 1, which provides support for dynamic types in C #, as well as dynamically programming languages such as IronPython and IronRuby.

Dynamic can simplify reflection.

We used reflection in this way before:

public class Dynamicsample
{public
string Name {get; set;}
public int Add (int a, int b)
{return
a + b;
}
}
Dynamicsample dynamicsample = new Dynamicsample (); Create instance in order to simplify the demo, I did not use reflection
var addmethod = typeof (Dynamicsample). GetMethod ("Add");
int re = (int) addmethod.invoke (dynamicsample, new object[] {1, 2});

Now, we have a simplified version of the wording:

Dynamic dynamicSample2 = new Dynamicsample ();
int Re2 = Dynamicsample2.add (1, 2);

We might disagree with this simplification, after all, it looks like the code hasn't diminished much, but if you take into account the two features of efficiency and elegance, the advantage of dynamic is apparent. The compiler optimizes dynamic and is much faster than the reflection without caching. If you want to compare, you can draw a conclusion by running 1000000 of the above code (calling the Add Method section).

COM Interoperability

C # 4.0 contains several features that improve interoperability with traditional COM API interfaces such as office automation. Dynamic types, named parameters, and optional parameters are also part of the improvement.

Many COM methods allow parameters and return value types to be object, so a large number of coercion type conversions are required for strongly typed languages such as C #. In C # 4.0, however, if you add the/link option at compile time, the dynamic type will have a new effect: It makes the object type (parameter type or return type) in the COM interface method signature considered dynamic, thus avoiding a large number of type conversion efforts. For example, the following statement compares this.

Dynamic is not used.
((Excel.Range) Excel. Cells[1, 1]). Value2 = "Name";
Excel.Range Range = (excel.range) Excel. Cells[1, 1];
With the dynamic, 
Excel. Cells[1, 1]. Value = "Name";
Excel.Range Range = Excel. Cells[1, 1];

The above is a small series to introduce the dynamic keyword in C # in the correct usage (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.