Skip to content

Instantly share code, notes, and snippets.

@ufcpp ufcpp/RefFor.cs
Created Apr 21, 2018

Embed
What would you like to do?
Cではよくやる p != end イテレーターループ
using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
var array = new[] { 1, 3, 5, 2, 4 };
PointerInit(array, 1);
Console.WriteLine(string.Join(", ", array));
RefInit(array, 2);
Console.WriteLine(string.Join(", ", array));
}
private unsafe static void PointerInit(int[] array, int value)
{
fixed (int* p = array)
{
// C 言語とかではよくやる書き方
var end = p + array.Length;
for (var i = p; i != end; i++)
{
*i = value;
}
}
}
private unsafe static void RefInit(int[] array, int value)
{
if (array.Length == 0) return;
ref var end = ref Unsafe.Add(ref array[0], array.Length);
for (ref var r = ref array[0]; !Unsafe.AreSame(ref r, ref end); r = ref Unsafe.Add(ref r, 1))
{
r = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.