CA2243:屬性字串常值必須正確剖析

屬性
規則識別碼 CA2243
標題 屬性字串常值必須正確剖析
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

屬性的字串常值參數無法正確剖析 URL、GUID 或 Version。

檔案描述

由於屬性衍生自 System.Attribute ,而且屬性會在編譯時期使用,因此只能將常數值傳遞至其建構函式。 必須表示 URL、GUID 和 Versions 的屬性參數無法輸入為 System.UriSystem.GuidSystem.Version ,因為這些類型不能表示為常數。 相反地,它們必須以字串表示。

因為參數的類型為字串,所以編譯時期可能會傳遞格式不正確的參數。

此規則會使用命名啟發學習法來尋找代表統一資源識別項(URI)、全域唯一識別碼(GUID)或版本的參數,並確認傳遞的值是否正確。

如何修正違規

將參數字串變更為格式正確的 URL、GUID 或版本。

隱藏警告的時機

如果 參數不代表 URL、GUID 或版本,則隱藏此規則的警告是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA2243
// The code that's violating the rule is on this line.
#pragma warning restore CA2243

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA2243.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

範例

下列範例顯示違反此規則的 AssemblyFileVersionAttribute 程式碼。

[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
[ComVisible(true)]
public sealed class AssemblyFileVersionAttribute : Attribute
{
    public AssemblyFileVersionAttribute(string version) { }

    public string? Version { get; set; }
}

// Since the parameter is typed as a string, it is possible
// to pass an invalid version number at compile time. The rule
// would be violated by the following code: [assembly : AssemblyFileVersion("xxxxx")]

規則是由下列參數所觸發:

  • 包含 'version' 且無法剖析為 System.Version 的參數。

  • 包含 'guid' 且無法剖析為 System.Guid 的參數。

  • 包含 'uri'、'urn' 或 'url' 的參數,無法剖析為 System.Uri。

另請參閱