3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

c# ref 構造体のメンバ関数でSpan<T>を受け取るときは拡張関数にしよう

Last updated at Posted at 2025-04-23

こういう書き方したいよね

param T[]って配列なのでヒープに乗りパフォーマンス低下。神のサイト
stackallocを使って以下のようにすれば大丈夫。

Hoge(stackalloc T[]{t0,t1,t2});
Hoge(stackalloc T[]{t3,t4});

ref構造体のメンバ関数では無理

拡張関数はstatic関数なのでいけるっぽい。

using System;
class Program
{
    public static void Main()
    {
        Span<int> span = stackalloc int[] { 1, 2, 3 };
        new TestRefStruct().A(span);// ここだけエラー
        new TestRefStruct().ExA(span);
        new TestClass().A(span);
        new TestStruct().A(span);
    }
}
public ref struct TestRefStruct
{
    public void A(Span<int> arg)
    {

    }
}
public static class ExTestStruct
{
    public static void ExA(this TestRefStruct ts,Span<int> arg)
    {

    }
}
public class TestClass
{
    public void A(Span<int> arg)
    {

    }
}
public struct TestStruct
{
    public void A(Span<int> arg)
    {

    }
}

C#11ではできるっぽい

コメントで教えてもらいました。
c#11以降ではscoped引数にすることで上の呼び出しが可能になるよ

public ref struct TestRefStruct
{
    public void A(scoped Span<int> arg)
    {
    }
}
3
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?