Correct use of dynamic in C #

Source: Internet
Author: User
Tags new set

Dynamic is a new feature of FrameWork4.0. The advent of dynamic gives C # The characteristics 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 attributes you want. For example, even if you know nothing about the objects returned by the Getdynamicobject method, you can call the code as follows, and the compiler will not error:

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

When it comes to proper usage, you should first point out a wrong usage:

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

This can be seen from the editor window of Visual Studio. Variables declared with VAR support IntelliSense because visual Studion can infer the actual type of the Var type, whereas a variable declared with dynamic does not support IntelliSense because the compiler knows nothing about the type of its run time. Using IntelliSense for dynamic variables prompts that this operation will resolve at run time.

About the dynamic variable is an object variable, which can be verified by IL code, where the IL code is no longer posted. Of course, the compiler also handles the dynamic declaration to differentiate the direct object variable.

The dynamic is being rendered by MSDN for ease of interoperability, and I feel that it is on this point that some developers misunderstand: because many developers do not touch the code such as COM +, office Two development, it is urgent to need a dynamic application justification. Well, in everyday development, I think the dynamic is valuable:

Type ConversionsConversions between instances of the dynamic type and other types of instances are straightforward, and developers can easily switch between dyanmic and non-dynamic behavior. Any instance can be implicitly converted to an instance of the dynamic type, as shown in the following example: Dynamic D1 = 7;dynamic D2 = "A string";d ynamic d3 = system.datetime.today;dynamic D4 = syste M.diagnostics.process.getprocesses (); Conversely, an implicit conversion can is dynamically applied to any expression of type dynamic. Or vice versa, any expressions of type dynamic can also be implicitly Convert to a different type. int i = d1;string str = d2;datetime dt = d3; system.diagnostics.process[] procs = D4; overload problem with dynamic type parameter in methodIf you call a method that passes an object of type dynamic, or if the object being called is of type dynamic, then the overload is judged to occur at runtime rather than at compile time. The dynamic Language runtime (Dynamic Language runtime DLR) is a new set of APIs in the. NET Framework 4 Beta 1 that provides support for the type of dynamics in C #. Dynamic programming languages like IronPython and IronRuby are also implemented.

dynamic can simplify reflection .

We used to use reflection like this 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 presentation, 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 notation: dynamic dynamicSample2 = new Dynamicsample ();
int Re2 = Dynamicsample2.add (1, 2); we might dismiss this simplification, after all, it doesn't look like the code is much less, but if you take into account the efficiency and the beauty of the two features, then the advantages of dynamic are apparent. The compiler optimizes dynamic for a much faster reflection efficiency than without caching. If you do not want to compare, you can run the code above (call the Add Method section) 1000000 to draw a conclusion.

Correct use of dynamic in C #

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.