Var, dynamic, and vardynamic

Source: Internet
Author: User

Var, dynamic, and vardynamic

Var and dynamic

If you have written a program using MVC, you should know that ViewBag is a data transfer tool for the front and back ends. Are you confused about the usage of ViewBag?

 

ViewBag.Mode1l=new object();ViewBag.Model2=new object();ViewBag.Model3=new object();......

 

We know that we need to declare the object Attribute before using it (that is, this attribute has been defined in the class of this object) (In this case, all the attributes of this class can be displayed in the automatic prompt of .)ViewBab.No attributes will pop up later (unless the attributes have been added earlier), and we can write an attribute by ourselves, but it can run correctly. This is all due to the property of dynamic.

1. Before talking about dynamic, let's review the var type.

From Visual C #3.0, variables declared in the method range can have implicit type var. Implicit local variables are strongly typed (as if you have declared this type), but the type is determined by the compiler. The following two I declarations are functionally equivalent:

Var I = 10; // implicitly typed (implicit Declaration) int I = 10; // explicitly typed (display Declaration)

  The var type is determined by the compiler (that is, during compilation, the compiler determines the type of the variable based on the value of the variable or the referenced object type ), however, once the type of the variable is determined, it cannot be changed.

Var I = 1; // I is int type, equivalent to int I = 1; I = 1.0; // error, 1.0 is double type

Note that var variables must be initialized during declaration, as shown below:

Var I = 1; // correct var I; I = 1; // Error

2. var usage example:

// Yes, but no var is required, because you can declare the type of the query result as IEnumerable <string> string [] words = {"apple", "strawberry ", "grape", "peach", "banana"}; var wordQuery = from word in words where word [0] = 'G' select word; // because the element type is string and not anonymous, var is not a required foreach (string s in wordQuery) {Console. writeLine (s);} // var must be used in the expression, because the result is an anonymous set, only the compiler can access var custQuery = from cust in mers MERs where cust. city = "Phoenix" select new {cust. name, cust. phone}; // The foreach iteration variable item must also be converted to the implicit type, because custQuery is an anonymous set foreach (var item in custQuery) {Console. writeLine ("Name = {0}, Phone = {1}", item. name, item. phone );}

3. dynamic

In operations implemented through the dynamic type, this type is used to bypass the type check during compilation and parse these operations at runtime. The dynamic type simplifies access to COM APIs (such as Office Automation APIs), dynamic APIs (such as the IronPython Library), and HTML document object models (DOM.

 

In most cases, the dynamic type and object type have the same behavior. However, the compiler will not be used to parse or check operations that contain dynamic expression types. The compiler packs the information about the operation together and then uses the information for computing runtime operations. In this process, the variables of the Type dynamic are compiled into the variables of the type object. Therefore, the Type dynamic only exists during compilation and does not exist during runtime.

 

Class Program {static void Main (string [] args) {dynamic dyn = 1; object obj = 1; dyn = dyn + 3; // compilation is successful, dynamic can bypass the compiler obj = obj + 3; // an error is reported and compilation fails through System. console. writeLine (dyn. getType (); System. console. writeLine (obj. getType () ;}// output result System. int32System. int32

 

4. Some common dynamic usage

(1) The declaration is a type of attribute, field, indexer, parameter, return value, or type constraint.

Class ExampleClass {// field static dynamic field; // attribute dynamic prop {get; set;} // return value and parameter public dynamic exampleMethod (dynamic d) {dynamic local = "Local variable"; int two = 2; if (d is int) {return local ;}else {return two ;}}}

(2) In explicit type conversion, as the target type of conversion.

static void convertToDynamic(){    dynamic d;    int i = 20;    d = (dynamic)i;    Console.WriteLine(d);    string s = "Example string.";    d = (dynamic)s;    Console.WriteLine(d);    DateTime dt = DateTime.Today;    d = (dynamic)dt;    Console.WriteLine(d);}// Results:// 20// Example string.// 2/17/2009 9:12:00 AM

  (3) Any context that acts as a value (such as the is operator or the right side of the as operator) as a type parameter or becomes part of the constructor type.

Int I = 8; dynamic d; if (someVar is dynamic) {} d = I as dynamic; Console. writeLine (typeof (List <dynamic>); // Console. writeLine (typeof (dynamic); // compilation Error

5. dynamic and ViewBab

  ViewBab is a dynamic type attribute, so the compiler does not check it, so we can customize the attribute. We can also use the ExpandoObject () class to implement our own ViewBab. See the following example:

Public class Program {public static void Main (string [] args) {dynamic model = new ExpandoObject (); // At runtime, the model is converted to ExpandoObject () an instance model. index = 0; // ExpandoObject () has an event PropertyChanged, which is triggered dynamically at runtime, model. number = 0; // Add the Index and Number attributes to the Console of the class. writeLine (model. index); Console. writeLine (model. number); Console. readKey ();}}

You may think that dynamic is not used much, so you don't need to understand it in depth, but it will suffer a big loss when you really encounter it. As mentioned above, it plays an important role in operations on the com api, dynamic API, and HTML object model. Through it, operations can be simplified, but at the same time, it is easy to confuse (what type of object it points to), because simplification usually means hiding, it encapsulates complex background implementations and opens simple interfaces for us to use. This simplifies our operations, but we are more confused. We don't know why it is doing this, we only know that we can do this, which makes it impossible for us to explore many problems in depth. In-depth understanding of dynamic in website development helps us to go deep into the framework, which is very helpful for us to learn about the. Net architecture.

 

 

 

Related Article

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.