| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA1421 |
| 職稱 | 方法會在套用 DisableRuntimeMarshallingAttribute 時使用運行時間封送處理 |
| 類別 | 互通性 |
| 修正程式是中斷或非中斷 | 不中斷 |
| 在 .NET 10 中預設啟用 | 建議 |
原因
方法會使用執行階段封送處理,而且明確停用執行階段封送處理。
檔案描述
如果某方法在執行時編組被關閉時仍嘗試進行執行時編組,可能會因類型原生佈局的不同期望而在執行時引起意想不到的行為差異。
如何修正違規
啟用運行時間封送處理或使用 和指標等 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 元件上的屬性。