Home > Backend Development > C#.Net Tutorial > Detailed explanation of anonymous objects, var and dynamic type dynamic in C#

Detailed explanation of anonymous objects, var and dynamic type dynamic in C#

黄舟
Release: 2017-09-06 13:53:03
Original
2564 people have browsed it

With the development of C#, the content of the language continues to be enriched, development becomes more convenient and faster, and the sharpness of C# is undoubtedly revealed. The C# language has been a strongly typed language since its birth. This nature has not changed today, and I think it will not change in the future. Since it is a strongly typed language, writing any program must meet the following basic conditions:

1. The variable declaration must indicate its type

2. After the variable type is clear, its type must be specified. The 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; }
    }
Copy after login
static void Main(string[] args)
{    int a = 10;    string s = "abc";
    Student student = new Student();    //下面出现编译错误,变量类型在声明后无法再变更
    s = a;
    student = s;
    a = 10.1f;
}
Copy after login

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

1. In a larger In a program, only one or a few places (no more than 3 places) need to use a certain type or types (such as Student above), and these types are no longer needed in other places. To declare a Student type separately, the amount of code required may exceed the amount of code when using this type, and the investment-output ratio is not cost-effective.

2. In a program, only some attributes or methods of a certain type of object are required to participate in the operation. In this case, temporarily converting this type of object into an object with some of the properties and methods required by the program can make the program more streamlined.

3. Other situations... I have not noticed yet... Welcome to add...

The above actual development of C# There are relatively good solutions to common problems in JavaScript development, as follows:

//在此处js中需要模拟一个学生对象
student = {"name":"张三","age":20,"like":"LOL"};
//在此处js中需要模拟一个老师对象
teacher = {"name":"李老师","like":"没收学生手机,自己LOL"};
//此处需要将学生student转换成只有name和age的对象
person = {"name":student.name,"age":student.age};
Copy after login

If you are not familiar with the above js syntax, you can go to Baidu to search for "json syntax" and I will tell you that it is very simple (and Very important).

Anonymous object (anonymous type)

Therefore, C# has absorbed the grammatical advantages of JavaScript script language in version 3.0, and has made corresponding upgrades to C# so that it can also This syntax form is supported (C# is still a strongly typed language). The sample code is as follows:

static void Main(string[] args)
{     new {Name="张三",Age=20,Like="LOL"};
}
Copy after login

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, followed by = and the corresponding value of the attribute. In this way, we avoid "To create an object, you must first have the constraints of the object type", Therefore, during the development process, we no longer need to create separate classes for less used types, the problems mentioned above 1 was resolved.

The object created now does not specify a specific type, so it is called anonymous object.

Var appears

Now to use an anonymous object, you need to use a variable to reference it. Although we do not specify the type of object when creating it, the compiler will help us create a type with related properties and methods during the compilation process. The type name compiled at this time is randomly generated, so the variable type cannot be determined. An example is as follows:

static void Main(string[] args)
{    //XXX为类型声明    //x为引用变量 
     XXX x = new {Name="张三",Age=20,Like="LOL"};
}
Copy after login

Although we don't know the type name generated by the compiler, we can let the compiler infer the variable type based on the compilation results. At this time, the var keyword comes into play:

static void Main(string[] args)
{     var x = new {Name="张三",Age=20,Like="LOL"};
}
Copy after login

The var keyword indicates that the type of Picture:

Notes on using var:

1. var can only declare local variables within methods

2. The type of the variable declared by var is determined after it is assigned, and other types of values ​​cannot be assigned in subsequent programs

3. var x = new object() makes no sense, don’t write such code.............

Now there is With the support of anonymous objects and var inferred types, we can deal with problem 2 mentioned above. The sample code is as follows:

        static void Main(string[] args)
        {            
        var x = new { Name = "张三", Age = 20, Like = "LOL" };            
        var s = new { Name = x.Name, Age = x.Age };  
        }
Copy after login

The above is just an example. If you are familiar with Linq or Entity Framework, the usage corresponding to question 2 will be overwhelming...

Dynamic type dynamic appears

The use of anonymous types is generally limited to the part of the method, which can be understood as: define it as you use it, and disappear after use. What should you do in the following situations?


        static void Main(string[] args)
        {            
        var x = GetObject(); 
        }        
        private static XXX GetObject()
        {            
        return new { Name = "张三", Age = 20, Like = "LOL" };
        }
Copy after login

Returns an anonymous object through the GetObject method, so the method return value type name cannot be determined, and is temporarily replaced by XXX here. In this case the return type is undefined and can be specified using dynamic . As follows:

          Main( x =    { Name = , Age = , Like =
Copy after login

At this time, there will be no syntax errors in the method, and the program can be successfully compiled and executed. So what exactly does dynamic do to make the above program compile successfully?

The role of dynamic:

1. Dynamic represents dynamic type. The meaning of dynamic type is that the type is uncertain during the program writing and compilation stages. At runtime, the properties or attributes of the relevant objects are determined through the reflection mechanism. method. Therefore, syntax checking is not 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 you cannot know what dynamic is when you write code (reflection)

Dynamic declared variables can be understood as object type variables. Therefore, it is correct to assign any type of value to a dynamic variable. However, when using a variable to obtain a property value or call a method (the program must be in the Runtime state at this time), the CLR will check (reflection) whether the called property or method exists. , there is no runtime exception reported.

dynamic is used everywhere in Asp.net Mvc web development. Although it looks complicated, the essence is what is mentioned above.

Explanation:

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

var dynamic
Declaration fields ×
Local variables
Method parameter type ×
Method return value type ×

The above is the detailed content of Detailed explanation of anonymous objects, var and dynamic type dynamic in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template