語言
| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA2259 |
| Title | 屬性無影響 |
| Category | Usage |
| 修正是破壞性或非破壞性 | 不中斷 |
| 預設啟用於 .NET 10 版本 | 作為警告 |
| 在 .NET 11 中預設啟用 | 作為警告 |
| 適用語言 | C# 與 Visual Basic |
原因
以下屬性之一被套用在其無效的位置:
- ThreadStaticAttribute, ContextStaticAttribute, 或 FixedAddressValueTypeAttribute 套用到實例欄位。
- FixedAddressValueTypeAttribute 套用於非結構體型別、非原始型別或枚舉型別的靜態欄位。
- SuppressGCTransitionAttribute 被套用於非 P/Invoke 的方法。
該規則也會檢查針對自動實作屬性或欄位類似事件的支援欄位的屬性,例如 [field: ThreadStatic]。
規則描述
有些屬性只在特定位置生效。 在其他地方,執行環境會忽略它們,程式碼也不會像表面看起來那樣運作。
-
ThreadStaticAttribute且ContextStaticAttribute僅影響
static(在 Visual Basic 中為Shared)欄位。 -
FixedAddressValueTypeAttribute 只影響屬於非原始型別且非列舉之結構類型的
static欄位。 - SuppressGCTransitionAttribute 僅影響 P/Invoke 方法。
規則不會標記其互操作來源產生器會遵循該屬性的方法上的 SuppressGCTransitionAttribute。 這些是標記為 LibraryImportAttribute 的方法,以及標記為 GeneratedComInterfaceAttribute 的介面的抽象執行個體方法。
如何修正違規
若要修正違規,請移除該屬性。 如果您是要讓該屬性生效,請變更成員,使其可套用,例如將欄位設為 static。
範例
以下程式碼片段顯示了 CA2259 的違規情況:
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class C
{
[ThreadStatic]
public int number = 404;
[FixedAddressValueType]
public static int s_count;
[SuppressGCTransition]
public static void DoWork() { }
}
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Class C
<ThreadStatic>
Public number As Integer = 404
<FixedAddressValueType>
Public Shared count As Integer
<SuppressGCTransition>
Public Shared Sub DoWork()
End Sub
End Class
隱藏警告的時機
忽略此規則的警告是安全的。 不過,這個屬性是 NOP,沒有達到你原本的預期效果。