Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created September 21, 2023 13:39
Show Gist options
  • Save ufcpp/7d9a750396590c2437198a1102242f44 to your computer and use it in GitHub Desktop.
Save ufcpp/7d9a750396590c2437198a1102242f44 to your computer and use it in GitHub Desktop.
Unsafe.AsRef implicit operator
using System.Runtime.CompilerServices;
var p = new Private();
Console.WriteLine(p.Value); // 0
Accessor r = p; // implicit cast で p の参照が r に渡る。
r.Value = 1;
Console.WriteLine(p.Value); // 書き変わってる。
// PrivateProxy 触りつつ、
// primary constructor 触りつつ遊んでて…
ref struct Accessor(ref Private x)
{
ref Private _x = ref x;
// もしや implicit cast 行けるのでは? (誰得)
public static implicit operator Accessor(in Private x) => new(ref Unsafe.AsRef(in x));
[UnsafeAccessor(UnsafeAccessorKind.Field)]
private static extern ref int _value(ref Private x);
public ref int Value => ref _value(ref _x);
}
struct Private
{
private int _value;
public readonly int Value => _value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment