Je commencerai les messages de 2023 (fin février :)) avec une petite casse-tête sur C#.
Compte tenu du programme ci-dessous, répondez aux questions suivantes:
1. Quelle est sa sortie ?
2. Pouvez-vous repérer/expliquer les problèmes dans le code ?
3. Comment identifier le problème ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
ref struct RefStruct | |
{ | |
public RefStruct(ref int i) => value = ref i; | |
public ref int value; | |
} | |
partial class C | |
{ | |
public static RefStruct Instantiate(ref int i) => new RefStruct(ref i); | |
unsafe static RefStruct InstantiateAndLog(int v) | |
{ | |
Console.WriteLine($"{nameof(RefStruct)} created."); | |
return Instantiate(ref v); | |
} | |
public static void M2(int v) | |
{ | |
Console.WriteLine("---------M2----------"); | |
var rs = Instantiate(ref v); | |
Dump(rs); | |
} | |
public static void M3(int v) | |
{ | |
Console.WriteLine("---------M3----------"); | |
var rs = InstantiateAndLog(v); | |
Dump(rs); | |
} | |
static void Dump(in RefStruct rs) | |
{ | |
var bytes = BitConverter.GetBytes(rs.value); | |
foreach(var b in bytes) | |
Console.WriteLine($"{b,2:x}"); | |
} | |
static void Main() | |
{ | |
const int Value = 0x01020304; | |
M2(Value); | |
M3(Value); | |
} | |
} |
A bientôt
Amusez-vous!
Adriano
No comments:
Post a Comment