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
var l = new List<PointStruct>() { | |
new PointStruct(1, 10), | |
new PointStruct(2, 20), | |
new PointStruct(3, 30), | |
}; | |
var a = l.ToArray(); | |
l.ForEachRef(static (ref PointStruct p) => p.Swap()); | |
foreach (var p in l) { | |
Console.WriteLine(p); | |
} | |
static class Extensions { | |
public delegate void RefAction<T>(ref T value) where T : struct; | |
public static void ForEachRef<T>(this List<T> list, RefAction<T> action) where T : struct { | |
if (list is null) throw new ArgumentNullException(nameof(list)); | |
if (action is null) throw new ArgumentNullException(nameof(action)); | |
var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(list); | |
foreach (ref T item in span) { | |
action(ref item); | |
} | |
} | |
} | |
struct PointStruct { | |
public int X, Y; | |
public PointStruct(int x, int y) { | |
X = x; | |
Y = y; | |
} | |
public void Swap() => this = new PointStruct(Y, X); | |
public double Dist => Math.Sqrt((X * X) + (Y * Y)); | |
public override string ToString() => $"({X.ToString()},{Y.ToString()})"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment