


Detailed explanation of anonymous objects, var and dynamic type dynamic in C#
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; } }
static void Main(string[] args) { int a = 10; string s = "abc"; Student student = new Student(); //下面出现编译错误,变量类型在声明后无法再变更 s = a; student = s; a = 10.1f; }
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};
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"}; }
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"}; }
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"}; }
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 }; }
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" }; }
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 =
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Setting up a wireless network is common, but choosing or changing the network type can be confusing, especially if you don't know the consequences. If you're looking for advice on how to change the network type from public to private or vice versa in Windows 11, read on for some helpful information. What are the different network profiles in Windows 11? Windows 11 comes with a number of network profiles, which are essentially sets of settings that can be used to configure various network connections. This is useful if you have multiple connections at home or office so you don't have to set it all up every time you connect to a new network. Private and public network profiles are two common types in Windows 11, but generally

Part 1 Let’s talk about the nature of Python sequence types. In this blog, let’s talk about Python’s various “sequence” classes and the three built-in commonly used data structures – list, tuple and character. The nature of the string class (str). I don’t know if you have noticed it, but these classes have an obvious commonality. They can be used to save multiple data elements. The most important function is: each class supports subscript (index) access to the elements of the sequence, such as using SyntaxSeq[i]. In fact, each of the above classes is represented by a simple data structure such as an array. However, readers familiar with Python may know that these three data structures have some differences: for example, tuples and strings cannot be modified, while lists can.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

Go functions can return multiple values of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

It’s great to use dynamic language for a while, and the code is reconstructed in the crematorium. I believe you must have heard this sentence. Like unit testing, although it takes a small amount of time to write code, it is very worthwhile in the long run. This article shares how to better understand and use Python's type hints. 1. Type hints are only valid at the syntax level. Type hints (introduced since PEP3107) are used to add types to variables, parameters, function parameters, and their return values, class properties, and methods. Python's variable types are dynamic and can be modified at runtime to add type hints to the code. It is only supported at the syntax level and has no impact on the running of the code. The Python interpreter will ignore the type hints when running the code. Therefore the type

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.
