Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created October 17, 2022 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/9383c8e4a2abd756a2248e23f925d5bf to your computer and use it in GitHub Desktop.
Save ufcpp/9383c8e4a2abd756a2248e23f925d5bf to your computer and use it in GitHub Desktop.
(stackalloc) + extension methods
// u8 リテラルの型は ReadOnlySpan<byte> なので、ROS に対する拡張メソッド直呼び可能。
""u8.R();
// それでふと思ったけども、stackalloc も行ける?
// 式の途中で stackalloc を書くと Span になる。
A.S(stackalloc byte[0]);
// この場合(拡張メソッドじゃなくて、静的メソッド呼びの場合)、 ReadOnlySpan への変換も働く。
A.R(stackalloc byte[0]);
unsafe
{
// ちなみに、これは byte* になっちゃう。
var p = stackalloc byte[0];
}
// でも、() で囲うと Span<byte> という。
var span = (stackalloc byte[0]);
// なので、これ、呼べるみたい。
(stackalloc byte[0]).S();
// が、そこにさらに Span → ReadOnlySpan の型変換が挟まるとダメ。
// 拡張メソッド解決時に暗黙の型変換は見ない。
(stackalloc byte[0]).R(); // この行だけエラー。
static class A
{
public static void R(this ReadOnlySpan<byte> _) { }
public static void S(this Span<byte> _) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment