我考虑在我的代码库中开始使用代码契约。
我已经在启用了所有规则并且目标为零警告的情况下使用代码分析。
但是,在使用Contract.Requires(parameter != null)时,我会从代码分析中得到一个警告,即CA1062:
CA1062 : Microsoft.Design :在外部可见的方法'Foo‘中,在使用参数之前验证参数’参数‘。
不幸的是,我不想禁用这条规则,因为我觉得它很有用。但我也不想压制它的每一个错误的发生。
有解决办法吗?
发布于 2015-07-26 15:31:57
从框架的4.5.2版本(甚至4.5)开始,就可以告诉Contracts关于由contracts强制执行的合同。首先创建以下扩展方法和标记属性
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
/// <summary>Extension methods to enhance Code Contracts and integration with Code Analysis.</summary>
public static class ContractExtensions {
#if RUNTIME_NULL_CHECKS
/// <summary>Throws <c>ArgumentNullException{name}</c> if <c>value</c> is null.</summary>
/// <param name="value">Value to be tested.</param>
/// <param name="name">Name of the parameter being tested, for use in the exception thrown.</param>
[ContractArgumentValidator] // Requires Assemble Mode = Custom Parameter Validation
public static void ContractedNotNull<T>([ValidatedNotNull]this T value, string name) where T : class {
if (value == null) throw new ArgumentNullException(name);
Contract.EndContractBlock();
}
#else
/// <summary>Throws <c>ContractException{name}</c> if <c>value</c> is null.</summary>
/// <param name="value">Value to be tested.</param>
/// <param name="name">Name of the parameter being tested, for use in the exception thrown.</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "name")]
[ContractAbbreviator] // Requires Assemble Mode = Standard Contract Requires
public static void ContractedNotNull<T>([ValidatedNotNull]this T value, string name) where T : class {
Contract.Requires(value != null,name);
}
#endif
}
/// <summary>Decorator for an incoming parameter that is contractually enforced as NotNull.</summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ValidatedNotNullAttribute : global::System.Attribute {}现在将条目空测试转换为以下格式:
/// <summary>IForEachable2{TItem} implementation</summary>
public void ForEach(FastIteratorFunctor<TItem> functor) {
functor.ContractedNotNull("functor"); // for Code Analysis
TItem[] array = _array;
for (int i = 0; i < array.Length; i++) functor.Invoke(array[i]);
}当然,方法名称ContractedNotNull和编译开关RUNTIME_NULL_CHECKS可以更改为适合您的命名风格的任何东西。
这是最初的博客告诉了我这项技术,我对此做了一些改进;非常感谢Terje Sandstrom发表了他的研究成果。
Rico通过使用其他属性扩展了这个这里,这样调试器和内联程序也更聪明了:
发布于 2012-11-09 12:57:24
要解决这个问题,需要执行以下步骤:
Contract.Requires。步骤1消除CA警告,步骤2至4启用至少等效的代码契约警告。
https://stackoverflow.com/questions/13273842
复制相似问题