Take you through C#7 feature code examples
Take you through C#7 feature code examples:
Tuple value type
.NET provides a tuple type, but there are various problems when using it in C#. Since the tuple type is a reference type, you can probably avoid the GC overhead of using it in some performance-sensitive code. At the same time, tuple types are immutable, and while this makes sharing across threads safer, it also means that a new object must be allocated every time a change is made.
To deal with this problem, C# 7 will provide a tuple of value types. This is a mutable type, which will be more efficient for code that values performance. Also, as a value type, it makes a copy every time it is allocated, so there is little risk of multi-threading issues.
You can create a tuple with the following syntax:
var result = (5, 20);
You can also choose to name the values in the tuple, which is not required but just makes the code more readable.
var result = (count: 5, sum: 20);
You might be thinking, "Great feature, but I can write it myself." But the next feature is the highlight.
Multiple return values
In C-like languages, returning two values from a function is always a hassle. You can only choose to encapsulate the result into some structure or use output parameters. Like many functional programming languages, C# chooses the first way to provide you with this feature:
(int, int) Tally (IEnumerable<int> list)
As you can see, there is a basic problem with using generic tuples here: we will have no way of knowing what each field does. Therefore, C# chooses to name the result via a compiler trick:
(int Count, int Sum) Tally (IEnumerable<int> list)
We need to emphasize one point here: C# does not generate a new anonymous type. What you get is still a tuple, but the compiler will assume that its properties are Count and Sum instead of Item1 and Item2. Therefore, the following lines of code are equivalent:
var result = Tally(list); Console.WriteLine(result.Item1); Console.WriteLine(result.Count);
Please note that we do not yet have multiple assignment syntax. If this syntax is finally implemented, its usage may be like this:
(count, sum) = Tally(list);
In addition to providing simple functional functions, the utility of multiple return values is also reflected in the writing of asynchronous code, because out parameters are not allowed in async functions.
Pattern Matching: Improved Switch syntax blocks
The most common complaint about C# from VB and functional programmers is that the switch statement in C# has very limited functionality. VB developers want to be able to do range matching, while developers who are used to F# or Haskell want to be able to use decomposed pattern matching. C# intends to provide both features.
When pattern matching a type, you can create a variable to hold the result of the cast. For example, when using the switch statement on a System.Object, you can write the following code:
case int x:
If the object is of numeric type, the variable x will be assigned a value. Otherwise, the program will check the next case statement block in order from top to bottom. If you want to be more specific with your match, you can also use range checking:
case int x when x > 0: case int y:
In this example, if the object is a positive integer, the x code block will be executed. If the object is 0 or a negative integer, the y code block will be executed.
If you need to check for null values, just use the following syntax:
case null;
Pattern Matching: Decomposition
So far, we have only shown some incremental improvements to existing features in VB. The real power of pattern matching lies in decomposition, which can completely take an object apart. Consider the following syntax:
if (person is Professor {Subject is var s, FirstName is "Scott"})
This code accomplishes two things:
It creates a local variable s and assigns it the value ((Professor)person).Subject.
It performs an equality check ((Professor)person).FirstName == "Scott".
If it is rewritten in C# 6 code, it will look like this:
var temp = person as Professor; if (temp != null && temp.FirstName == "Scott") { var s = temp.Subject
In the final release, we expect to see both improvements to switch blocks.
Return
Passing a large data structure by reference is much faster than passing by value, which requires a copy of the entire structure. Similarly, returning a reference to a large data structure can also improve speed.
In languages like C, you can return a reference to a structure through a pointer. This approach brings about a common problem, that is, the memory pointed to by the pointer may have been reclaimed for some reason.
C# avoids this problem by using a reference, which is a pointer with rules attached. The most important rule is that you cannot return a reference to a local variable. If you try to do this, the stack information referenced by the variable will become inaccessible when the function returns.
在微软的展示代码中,它所返回的引用指向一个数组中的某个结构。由于它实质上是指向数组中某个元素的指针,因此随后可以对数组本身进行修改。举例来说:
var x = ref FirstElement(myArray) x = 5; //MyArray[0] now equals 5
这一语法的用例是对性能高度敏感的代码,在大多数应用中都无需使用这一特性。
二进制字面值(Binary Literals)
此次发布还引入了一个小特性,即二进制字面值。这一语法只是一个简单的前缀而已,例如5可以表示为“0b0101”。这一特性的主要用例是设置基于flag的枚举,以及创建位掩码(bitmask),以用于与C风格语言的互操作。
本地函数
本地函数是指在另一个函数中所定义的函数。第一眼看来,本地函数似乎只是比匿名函数稍好的一种语法。但它实际上还存在几个优点:
首先,你无需为其分配一个委托以保存该函数。这不仅减少了内存压力,同时还允许编译器对该函数进行内联操作。
其次,在创建闭包时,也无需为其分配一个对象,因为它能够直接访问本地变量。这一点同样能够改善性能,因为它也减少了GC的压力。
按照第二条规则推算,你将无法创建一个指向本地函数的委托。这一点对于代码的组织其实是一个优点,因为你无需创建独立的函数,并且将现有函数的状态作为显式的参数进行传递。
部分类的改进
最后演示的特性是一种处理部分类的新方式。在过去,部分类的应用是基于代码生成优先的概念而出现的。所生成的代码将包含一系列部分方法,开发者可以选择实现这些方法,以调整类的行为。
通过新的“replace”语法,开发者就多了一种新选择,能够以最直接的方式编写代码,随后再引入代码生成器,并重写这些方法。以下将通过一个简单的示例表现开发者的代码编写方式:
public string FirstName {get; set;}
简单又清晰,但完全不符合XAML风格应用的写法。因此,代码生成器将生成如下代码:
private string m_FirstName; static readonly PropertyChangedEventArgs s_FirstName_EventArgs =new PropertyChangedEventArgs("FirstName") replace public string FirstName { get { return m_FirstName; } set { if (m_FirstName == value) return; m_FirstName = value; PropertyChanged?.Invoke(this, m_FirstName_EventArg); }
通过“replace”关键字,所生成的代码将直接替换手写的代码,添加所缺失的功能。在这个示例中,我们甚至还能够处理一些开发者经常会忽略的麻烦的部分,例如对EventArgs对象进行缓存。
虽然这个官方示例仅用于属性变更通知,但这一技术还可用于各种“面向切面编程(AOP)”的场景,例如在代码中注入日志记录、安全检查、参数校验以及其他各种繁琐的样板式代码。
如果读者想实际了解一下这些特性,可以观赏Channel 9中的视频“The Future of C#”。
The above is the detailed content of Take you through C#7 feature code examples. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











Everyone knows that there are many versions of win7 system, such as win7 ultimate version, win7 professional version, win7 home version, etc. Many users are entangled between the home version and the ultimate version, and don’t know which version to choose, so today I will Let me tell you about the differences between Win7 Family Meal and Win7 Ultimate. Let’s take a look. 1. Experience Different Home Basic Edition makes your daily operations faster and simpler, and allows you to access your most frequently used programs and documents faster and more conveniently. Home Premium gives you the best entertainment experience, making it easy to enjoy and share your favorite TV shows, photos, videos, and music. The Ultimate Edition integrates all the functions of each edition and has all the entertainment functions and professional features of Windows 7 Home Premium.

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

With the rapid development of the Internet, programming languages are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

The three characteristics of 5g are: 1. High speed; in practical applications, the speed of 5G network is more than 10 times that of 4G network. 2. Low latency; the latency of 5G network is about tens of milliseconds, which is faster than human reaction speed. 3. Broad connection; the emergence of 5G network, combined with other technologies, will create a new scene of the Internet of Everything.

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of a circle of a given radius and returns it as output.

The characteristics of Java are: 1. Simple and easy to learn; 2. Object-oriented, making the code more reusable and maintainable; 3. Platform-independent, able to run on different operating systems; 4. Memory management, through automatic garbage collection mechanism Manage memory; 5. Strong type checking, variables must declare their type before use; 6. Security, which can prevent unauthorized access and execution of malicious code; 7. Multi-threading support, which can improve the performance and responsiveness of the program ; 8. Exception handling can avoid program crashes; 9. A large number of development libraries and frameworks; 10. Open source ecosystem.

Five highlight features of PHP8 to make your code more efficient! PHP (Hypertext Preprocessor) is a widely used open source scripting language for web development. It is easy to learn, can be used nested with HTML, and also supports object-oriented programming. As the latest version, PHP8 has many exciting new features and improvements. Here are five main highlights that can make your code more efficient. 1. JIT compiler (Just-In-TimeCompile
