CA2243:特性字符串文本应正确分析

属性
规则 ID CA2243
标题 特性字符串文本应正确分析
类别 使用情况
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

特性的字符串文本参数不能正确解析为 URL、GUID 或版本。

规则说明

由于特性从 System.Attribute 派生而来,并在编译时使用,因此只能将常数值传递给其构造函数。 必须表示 URL、GUID 和版本的特性参数不能类型化为 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 的参数。

另请参阅