Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the main language regions in C #

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about what are the main language areas in C#. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Arrays, collections and LINQ

C # and .NET provide many different collection types. The array contains syntax defined by the language. Generic collection types are listed in the System.Collections.Generic namespace. Dedicated collections include System.Span (for accessing contiguous memory on stack frames) and System.Memory (for accessing contiguous memory on the managed heap). All collections, including arrays, Span, and Memory, follow a unified iterative principle. Use the System.Collections.Generic.IEnumerable interface. This unified principle means that any collection type can be used with LINQ queries or other algorithms. You can use the IEnumerable writing method, and these algorithms apply to any collection.

1. Array

An array is a data structure * _ that contains many variables accessed through a computational index. The variables in the array (also known as the "elements" of the array) are of the same type. We call this type the "element type" of the array.

Array types are reference types, and declaring array variables only reserves space for reference array instances. The actual array instance is created dynamically at run time using the new operator. The new operation specifies the length of the new array instance, which is then used permanently for the lifetime of the instance. The index of array elements is between 0 and Length-1. The new operator automatically initializes array elements to their default values (for example, 0 for all numeric types and null for all reference types).

The following example creates an array of int elements, initializes the array, and then prints the contents of the array.

Int [] a = new int [10]; for (int I = 0; I

< a.Length; i++){ a[i] = i * i;}for (int i = 0; i < a.Length; i++){ Console.WriteLine($"a[{i}] = {a[i]}");} 此示例创建并在"一维数组"上进行操作。 C# 还支持多维数组。 数组类型的维数(亦称为数组类型的秩)是 1 与数组类型方括号内的逗号数量相加的结果。 以下示例分别分配一维、二维、三维数组。 int[] a1 = new int[10];int[,] a2 = new int[10, 5];int[,,] a3 = new int[10, 5, 2]; a1 数组包含 10 个元素,a2 数组包含 50 个元素 (10 × 5),a3 数组包含 100 个元素 (10 × 5 × 2)。 数组的元素类型可以是任意类型(包括数组类型)。 包含数组类型元素的数组有时称为"交错数组",因为元素数组的长度不必全都一样。 以下示例分配由 int 数组构成的数组: int[][] a = new int[3][];a[0] = new int[10];a[1] = new int[5];a[2] = new int[20]; 第一行创建包含三个元素的数组,每个元素都是 int[] 类型,并且初始值均为 null。 接下来的代码行将这三个元素初始化为引用长度不同的各个数组实例。 通过 new 运算符,可以使用"数组初始值设定项"(在分隔符 { 和 } 内编写的表达式列表)指定数组元素的初始值。 以下示例分配 int[],并将其初始化为包含三个元素。 int[] a = new int[] { 1, 2, 3 }; 可从 { 和 } 内的表达式数量推断出数组的长度。 数组初始化可以进一步缩短,这样就不用重新声明数组类型了。 int[] a = { 1, 2, 3 }; 以上两个示例等同于以下代码: int[] t = new int[3];t[0] = 1;t[1] = 2;t[2] = 3;int[] a = t; foreach 语句可用于枚举任何集合的元素。 以下代码从前一个示例中枚举数组: foreach (int item in a){ Console.WriteLine(item);} foreach 语句使用 IEnumerable 接口,因此适用于任何集合。 二、字符串内插 C# 字符串内插使你能够通过定义表达式(其结果放置在格式字符串中)来设置字符串格式。 例如,以下示例从一组天气数据显示给定日期的温度: Console.WriteLine($"The low and high temperature on {weatherData.Date:MM-DD-YYYY}");Console.WriteLine($" was {weatherData.LowTemp} and {weatherData.HighTemp}.");// Output (similar to):// The low and high temperature on 08-11-2020// was 5 and 30. 内插字符串通过 $ 标记来声明。 字符串插内插计算 { 和 } 之间的表达式,然后将结果转换为 string,并将括号内的文本替换为表达式的字符串结果。 第一个表达式 ({weatherData.Date:MM-DD-YYYY}) 中的 : 指定格式字符串。 在前一个示例中,这指定日期应以"MM-DD-YYYY"格式显示。 三、模式匹配 C# 语言提供模式匹配表达式来查询对象的状态并基于该状态执行代码。 你可以检查属性和字段的类型和值,以确定要执行的操作。 switch 表达式是模式匹配的主要表达式。 四、委托和 Lambda 表达式 委托类型表示对具有特定参数列表和返回类型的方法的引用。 通过委托,可以将方法视为可分配给变量并可作为参数传递的实体。 委托还类似于其他一些语言中存在的"函数指针"概念。 与函数指针不同,委托是面向对象且类型安全的。 下面的示例声明并使用 Function 委托类型: delegate double Function(double x);class Multiplier{ double _factor; public Multiplier(double factor) =>

_ factor = factor; public double Multiply (double x) = > x * _ factor;} class DelegateExample {static double [] Apply (double [] a, Function f) {var result = new double [a.Length]; for (int I = 0; I

< a.Length; i++) result[i] = f(a[i]); return result; } public static void Main() { double[] a = { 0.0, 0.5, 1.0 }; double[] squares = Apply(a, (x) =>

X * x); double [] sines = Apply (a, Math.Sin); Multiplier m = new (2.0); double [] doubles = Apply (a, m.Multiply);}}

An instance of the Function delegate type can reference a method that needs to use the double argument and return a double value. The Apply method applies the given Function to the element of double [], returning the double [] that contains the result. In the Main method, Apply is used to apply three different functions to double [].

A delegate can reference a static method (such as Square or Math.Sin in the example above) or an instance method (such as m.Multiply in the example above). A delegate that references an instance method also references a specific object that becomes the this in the call when the instance method is called through the delegate.

You can also create delegates using anonymous functions or Lambda expressions, which are "inline methods" created at the time of declaration. Anonymous functions can view the local variables of the surrounding methods.

The following example does not create a class:

Double [] doubles = Apply (a, (double x) = > x * 2.0)

A class that the delegate does not know or care about the method it refers to. The referenced method must have the same parameters and return type as the delegate.

5. Async/await

C # supports asynchronous programs with two keywords: async and await. Add the async modifier to the method declaration to declare that this is an asynchronous method. The await operator tells the compiler to wait for the result to complete asynchronously. Control returns to the caller, and the method returns a structure that manages asynchronous working state. The structure is usually System.Threading.Tasks.Task, but it can be any type that supports awaiter schema. These features enable you to write code that is read as its synchronous counterpart but executed asynchronously. For example, the following code downloads the home page of Microsoft Docs:

Public async Task RetrieveDocsHomePage () {var client = new HttpClient (); byte [] content = await client.GetByteArrayAsync ("https://docs.microsoft.com/"); Console.WriteLine ($" {nameof (RetrieveDocsHomePage)}: Finished downloading. "); return content.Length;}

This small example shows the main functions of asynchronous programming:

The method declaration contains the async modifier.

The body of the method await is the return of the GetByteArrayAsync method.

The type specified in the return statement matches the type parameter in the method's Task declaration. The method that returns Task will use the return statement without any parameters.

VI. Attributes

Types, members, and other entities in a C # program support the use of modifiers to control certain aspects of their behavior. For example, the accessibility of a method is controlled by the public, protected, internal, and private modifiers. C # integrates this capability so that declarative information of user-defined types can be attached to program entities and retrieved at run time. The program specifies this declarative information by defining and using properties.

The following example declares the HelpAttribute feature, which can be attached to a program entity to provide a link to the associated document.

Public class HelpAttribute: Attribute {string _ url; string _ topic; public HelpAttribute (string url) = > _ url = url; public string Url = > _ url; public string Topic {get = > _ topic; set = > _ topic = value;}}

All feature classes are derived from the Attribute base class provided by the .NET library. Properties are applied by specifying the name of the property and any arguments in square brackets before the relevant declaration. If the name of the property ends with Attribute, you can omit this part of the name when referencing the property. For example, you can use HelpAttribute as follows.

[Help ("https://docs.microsoft.com/dotnet/csharp/tour-of-csharp/features")]public class Widget {[Help (" https://docs.microsoft.com/dotnet/csharp/tour-of-csharp/features", Topic = "Display")] public void Display (string text) {}}

This example appends HelpAttribute to the Widget class. Another HelpAttribute is also attached to the Display method in this class. The common constructor of the property class controls the information that must be provided when the property is attached to the program entity. Additional information can be provided by referencing the public read-write properties of the property class (such as the reference to the Topic property in the example above).

You can use reflection at run time to read and manipulate the metadata defined by the property. If you use this method to request a specific property, the constructor of the property class (which provides information in the program source) is called. Returns the generated property instance. If additional information is provided through properties, these properties are set to the given value before the property instance is returned.

The following code example shows how to get the HelpAttribute instance associated with the Widget class and its Display method.

If (displayMethodAttributes.Length > 0) {HelpAttribute attr = (HelpAttribute) displayMethodAttributes [0]; Console.WriteLine ($"Display method help URL: {attr.Url}-Related topic: {attr.Topic}");} thanks for reading! This is the end of the article on "what are the main language areas in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report