如何使自定义NullReferenceException符合SonarCloud规范(.NET 8)
.NET 8自定义NullReferenceException兼容SonarCloud合规方案
我定义了如下自定义NullReferenceException类:
namespace BO.Application.Shared.Errors; using System; using System.Globalization; using System.Runtime.Serialization; [Serializable] public class NullReferenceException : System.NullReferenceException { private const string ErrorMessage = "VariableNotSet:{0}"; public NullReferenceException() { } public NullReferenceException(string message, System.Exception innerException) : base(message, innerException) { } public NullReferenceException(string name) : base(string.Format(CultureInfo.InvariantCulture, ErrorMessage, name)) { } protected NullReferenceException(SerializationInfo info, StreamingContext context) #pragma warning disable SYSLIB0051 // Type or member is obsolete : base(info, context) #pragma warning restore SYSLIB0051 // Type or member is obsolete { } }
当前面临的矛盾:
- 为满足SonarCloud合规要求,必须保留受保护的序列化构造函数
- 该构造函数在.NET 8中已过时,Roslyn分析器会抛出
SYSLIB0051警告 - 若标记构造函数为过时,SonarCloud要求移除过时代码
- 若直接抑制Roslyn警告,SonarCloud禁止此类问题抑制
可行方案:结合特性标记与Sonar局部豁免注释
通过以下调整,既满足序列化需求,又能通过SonarCloud合规检查:
namespace BO.Application.Shared.Errors; using System; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; [Serializable] public class NullReferenceException : System.NullReferenceException { private const string ErrorMessage = "VariableNotSet:{0}"; public NullReferenceException() { } public NullReferenceException(string message, System.Exception innerException) : base(message, innerException) { } public NullReferenceException(string name) : base(string.Format(CultureInfo.InvariantCulture, ErrorMessage, name)) { } // NOSONAR: Required for serialization compatibility with legacy systems [Obsolete("This constructor is only for serialization purposes and should not be called directly.")] [EditorBrowsable(EditorBrowsableState.Never)] protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { } }
方案说明:
- 添加
[Obsolete]属性明确标记构造函数的用途,避免误调用 - 用
[EditorBrowsable(EditorBrowsableState.Never)]隐藏该构造函数,防止在编辑器智能提示中出现 - 通过
// NOSONAR注释向SonarCloud说明保留该代码的必要性(序列化兼容),Sonar会豁免对此行的过时代码检查 - 移除原有的
#pragma warning disable,改用特性标记让代码更清晰,同时符合Roslyn的规范
这样调整后,既保留了序列化所需的构造函数,又不会触发Roslyn的过时警告,同时SonarCloud会因为明确的注释理由而接受这段代码,无需关闭任何规则。
内容的提问来源于stack exchange,提问作者Jester
相关产品推荐
相关产品推荐

