« Csharp 8 » : différence entre les versions
De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 73 : | Ligne 73 : | ||
</kode> | </kode> | ||
= Null-coalescing assignment / ?? <nowiki>=</nowiki> | = Null-coalescing assignment / ?? <nowiki>=</nowiki> = | ||
<kode lang='cs'> | <kode lang='cs'> | ||
int? i = null; | int? i = null; | ||
Ligne 81 : | Ligne 81 : | ||
i ??= 20; // assign 20 to i if i is null | i ??= 20; // assign 20 to i if i is null | ||
</kode> | </kode> | ||
= Nullable reference types = | |||
<filebox fn='MyProject.csproj' lang='xml'> | |||
<Project Sdk="Microsoft.NET.Sdk"> | |||
<PropertyGroup> | |||
<TargetFramework>netcoreapp3.1</TargetFramework> | |||
<Nullable>enable</Nullable> | |||
</filebox> | |||
= [https://stackoverflow.com/questions/56651472/does-c-sharp-8-support-the-net-framework .NET Framework] = | = [https://stackoverflow.com/questions/56651472/does-c-sharp-8-support-the-net-framework .NET Framework] = |
Version du 4 mars 2020 à 16:23
Liens
Switch expression
switch (i) { case 1: return "One"; default: throw new Exception("Invalid value"); } i switch { 1 => "One", _ => throw new Exception("Invalid value") }; |
Using declaration
using (var file = new StreamWriter("MyFile.txt")) { // some code } // file is disposed here void MyMethod() { using var file = new StreamWriter("MyFile.txt"); // some code // file is disposed here, at the end of the enclosing scope } |
Static local function
int x = 5; int y = 7; return Add(x, y); // Can be static because it doesn't access any variables in the enclosing scope static int Add(int left, int right) => left + right; |
Asynchronous streams / async yield
public static async IAsyncEnumerable<int> GenerateSequence() { for (int i = 0; i < 20; i++) { await Task.Delay(100); yield return i; } } await foreach (var number in GenerateSequence()) { Console.WriteLine(number); } |
Indices and ranges
var latest = myList[^1]; var secondToFour = myList[2..5]; var lastTwo = myList[^2..^0]; var firstThree = myList[..4]; var allExceptFirst = myList[2..]; |
Null-coalescing assignment / ?? =
int? i = null; i = i == null ? 20 : i; i ??= 20; // assign 20 to i if i is null |
Nullable reference types
MyProject.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <Nullable>enable</Nullable> |
.NET Framework
The C# 8 / .NET Framework combination is not officially supported by Microsoft.
It can be forced by editing the csproj file.
MyProject.csproj |
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <LangVersion>8.0</LangVersion> |
- default interface members won't work
- ssynchronous streams and indices and ranges will need polyfill nuget package