C # anonymous object (anonymous type), var, dynamic type dynamic,

Source: Internet
Author: User

C # anonymous object (anonymous type), var, dynamic type dynamic,

This article is the prelude to the next article "C # reflection and optimization usage". It is not the foundation of the next article. If you are interested, please pay attention to it.

With the development of C #, the content of the language is constantly enriched, and the development becomes more convenient and quick. The sharpness of C # is no doubt. C # language is a strong language since its birth. It has never changed so far, and I don't think it will change in the future. Since it is a strongly typed language, writing any program requires the following basic conditions:

1. The variable declaration must specify its type

2. After the variable type is clear, its type cannot be changed at Runtime.

The Code is as follows:

    public  class Student    {        public string Name { get; set; }        public int Age { get; set; }        public string Like { get; set; }    }
Static void Main (string [] args) {int a = 10; string s = "abc"; Student student = new Student (); // The following compilation error occurs, the variable type cannot be changed after it is declared. s = a; student = s; a = 10.1f ;}

However, in actual development, we often face the following common problems:

1. In a large program, only one or a few places (no more than three places) need to use one or some types (such as Student ), these types are no longer needed elsewhere. Declare a Student type separately. The amount of code required may exceed the amount of code used for this type. The input-output ratio is not cost-effective.

2. In a program, only some attributes or methods of certain types of objects are required for calculation. In this case, you can temporarily convert an object of this type to an object of some properties and methods required by the program, which can simplify the program.

3. Other situations ........

The above C # common problems in actual development, there are good solutions in JavaScript development, as follows:

// Student = {"name": "Zhang San", "age": 20, "like": "LOL"} needs to be simulated in js "}; // In this js, You need to simulate a teacher's object teacher = {"name": "", "like": "Student's mobile phone is confiscated, LOL by yourself "}; // student must be converted to the object person = {"name": student. name, "age": student. age };

If you are not familiar with the above js syntax, you can go to Baidu to search for "json Syntax", which is very simple (and important ).

Anonymous object (anonymous type)

Therefore, C #3.0 incorporates the syntax advantages of the JavaScript scripting language and upgrades C # To support this syntax form (C # is still a strong language). The sample code is as follows:

Static void Main (string [] args) {new {Name = "zhangsan", Age = 20, Like = "LOL "};}

The above C # code uses the new Keyword to tell the compiler to create an object. The object has three attributes: Name, Age, and Like. The value corresponding to the property is after =. So we avoided"To create an object, you must first have the constraints for this object type ",Therefore, in the development process, we do not need to create a separate class for a small number of types. Problem 1 mentioned above is solved..

Currently, no specific type is specified for the created object.Anonymous object.

Var debut

To use an anonymous object, you must reference it with a variable. Although we didn't specify the object type during creation, the compiler will help us create a type with relevant attributes and methods during compilation. The compiled type name is randomly generated, so the variable type cannot be determined. Example:

Static void Main (string [] args) {// XXX is the type declaration // x is the reference variable XXX x = new {Name = "Zhang San", Age = 20, like = "LOL "};}

Although we do not know the type name generated by the compiler, we canLet the compiler deduce the variable type based on the Compilation result.Now the var keyword plays a role:

 

Static void Main (string [] args) {var x = new {Name = "zhangsan", Age = 20, Like = "LOL "};}

The var keyword indicates that the type of x is determined by the value assigned (presumed), and smart prompts can be provided based on the compiler's suggestion, such:

Notes for using var:

1. var can only declare local variables in the Method

2. The variable declared by var is determined by the type after being assigned a value. Other types of values cannot be assigned in subsequent programs.

3. var x = new object () is meaningless. Do not write such code ...............

Now with support for anonymous objects and var inference types, we can handle problem 2 mentioned above. The sample code is as follows:

Static void Main (string [] args) {var x = new {Name = "zhangsan", Age = 20, Like = "LOL "}; var s = new {Name = x. name, Age = x. age };}

The above is only an example. If you are familiar with the Linq or Entity Framework, the usage of Question 2 will be overwhelming .......

Dynamic appearance

The use of the anonymous type is generally limited to the partial part of the method, which can be understood: It disappears when it is used up.What should I do in the following situations?

Static void Main (string [] args) {var x = GetObject ();} private static XXX GetObject () {return new {Name = "James", Age = 20, like = "LOL "};}

The GetObject method returns an anonymous object. Therefore, the type name of the method return value cannot be determined. XXX is used for the moment. In this case, the returned type is uncertain and can be specified using dynamic. As follows:

Static void Main (string [] args) {var x = GetObject ();
Console. WriteLine (x. Name);} private static dynamic GetObject () {return new {Name = "James", Age = 20, Like = "LOL "};}

At this time, the method will not have syntax errors, and the program can be compiled and executed successfully. So what exactly does dynamic do? Can the above program be compiled successfully?

Role of dynamic:

1. dynamic indicates the dynamic type. The meaning of the dynamic type is that the types of programming and compilation phases are uncertain. In Runtime, the attributes or methods of related objects are determined through the reflection mechanism. Therefore, no syntax check is performed during the writing phase.

2. dynamic can be used to declare fields, attributes, method parameters, and method return values.

3. dynamic does not support smart prompts, because when you write code, dynamic cannot know (reflection)

The variables declared by dynamic can be understood as object-type variables. Therefore, it is correct to assign any type value to the dynamic variable. However, when a variable is used to obtain a property value or call a method (the program must be in the Runtime state), the CLR checks (reflection) whether the called property or method exists. If no exception is reported during running.

Dynamic is used everywhere in Asp.net Mvc web development. Although it looks complicated, it is essentially the content mentioned above.

Note:

Var and dynamic seem to have similar functions, but they are different:

  Var Dynamic
Declared Field ×
Local variable
Method parameter type ×
Method Return Value Type ×

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.