CA1421:套用 'DisableRuntimeMarshallingAttribute ' 時,方法會使用執行階段封送處理

屬性
規則識別碼 CA1421
標題 方法會在套用 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 元件上的 屬性。