CA1421: DisableRuntimeMarshallingAttribute が適用されている場合、メソッドにはランタイム マーシャリングを使う

プロパティ
ルール ID CA1421
Title DisableRuntimeMarshallingAttribute が適用されている場合、メソッドにはランタイム マーシャリングを使う
[カテゴリ] 相互運用性
修正が中断ありか中断なしか なし
.NET 8 では既定で有効 提案として

原因

メソッドにランタイム マーシャリングを使い、ランタイム マーシャリングは明示的に無効にします。

規則の説明

ランタイム マーシャリングが無効なときにメソッドにランタイム マーシャリングを使うと、型のネイティブ レイアウトの想定が異なるため、実行時に予期しない動作の違いが発生する可能性があります。

違反の修正方法

正確な結果を得るには、ランタイム マーシャリングを有効にするか、sizeof やポインターのような機能を使います。

どのようなときに警告を抑制するか

この規則による警告は抑制しないでください。

次のコード スニペットは CA1421 の違反を示しています。

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: DisableRuntimeMarshalling]

class C
{
    public void Test()
    {
        nint offset = Marshal.OffsetOf(typeof(ValueType), "field");
    }
}

struct ValueType
{
    int field;
}

Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices

<Assembly: DisableRuntimeMarshalling>

Class C
    Shared Sub S1()
        Dim offset As IntPtr = Marshal.OffsetOf(GetType(ValueType), "field")
    End Sub
End Class

Structure ValueType
    Dim field As Integer
End Structure

この違反を修正するには、アセンブリの DisableRuntimeMarshallingAttribute 属性を削除します。