« Csharp 12 » : différence entre les versions
Apparence
Aucun résumé des modifications |
|||
Ligne 30 : | Ligne 30 : | ||
// concat items from different collections with the spread element: ..e | // concat items from different collections with the spread element: ..e | ||
int[] all = [.. a, .. l]; // [1, 2, 3, 4, 5, 6]; | int[] all = [.. a, .. l]; // [1, 2, 3, 4, 5, 6]; | ||
</kode> | |||
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#ref-readonly-modifier ref readonly modifier] = | |||
<kode lang='cs'> | |||
var item = new Item("name"); | |||
ForceByRef(ref item); | |||
static void ForceByRef(ref readonly Item item) | |||
{ | |||
item = new Item("new name"); // you can't assign a readonly variable | |||
item.Name = "new name"; // you can modify the object properties | |||
} | |||
</kode> | </kode> |
Version du 24 mai 2024 à 13:49
Links
Primary constructors
public class Item
{
public readonly string Name { get; }
public Item (string name)
{
Name = name;
}
}
// equivalent with a primary constructor
public class Item(string name)
{
public readonly string Name { get; } = name;
}
|
Collection Expressions
// initialization
int[] a = [1, 2, 3];
List<int> l = [4, 5, 6];
// concat items from different collections with the spread element: ..e
int[] all = [.. a, .. l]; // [1, 2, 3, 4, 5, 6];
|
ref readonly modifier
var item = new Item("name");
ForceByRef(ref item);
static void ForceByRef(ref readonly Item item)
{
item = new Item("new name"); // you can't assign a readonly variable
item.Name = "new name"; // you can modify the object properties
}
|