如何使代码合同忽略特定的程序集引用? [英] How can I make Code Contracts ignore a specific assembly reference?
问题描述
我正在扩展Visual Studio.在代码中,我使用代码契约进行断言和检查.我将警告选项级别设置为高.
I'm making an extension to Visual Studio. Within the code I'm using Code Contracts to make assertions and checks. I set the warning option level to high.
我想做的是保持该警告级别,而忽略对EnvDTE引用所做的任何检查.
What I would like to do is maintain that warning level while ignoring any checks made on EnvDTE references.
考虑以下代码示例:
public static string GetAbsoluteOutputFolder(EnvDTE.Project project)
{
if (project == null) throw new ArgumentNullException("project");
var path =
project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
//...
}
使用当前设置,CC会要求我在分配path
变量之前添加以下检查:
With my current settings, CC would require me to add the following checks before assigning the path
variable:
Contract.Assume(project.ConfigurationManager != null);
Contract.Assume(project.ConfigurationManager.ActiveConfiguration != null);
Contract.Assume(project.ConfigurationManager.ActiveConfiguration.Properties != null);
因此,我在这里要做的就是告诉CC信任" EnvDTE,并忽略这些类型及其属性.
Therefore what I'd like to do here is to tell CC to "trust" EnvDTE and ignore these types and their properties.
我认为对外部API保持乐观" CC选项正是出于这个目的;事实并非如此.
I thought the "Be optimistic on external API" CC option served this very purpose; turns out it doesn't.
是否有一种方法可以使其表现出我想要的不需要较低警告等级的方式?
Is there a way to make it behave the way I want that would not require a lower warning level?
编辑:我想要一个可以在项目级别工作并且仍然允许执行常规"检查的解决方案.
I want a solution that would work at project level and that would still allow "regular" checks to be performed.
推荐答案
无法提供详细的解决方案,但是应该可以通过在组装级别使用Baseline Feature或System.Diagnostics.CodeAnalysis.SuppressMessage来解决此问题:
Can´t provide a detailed solution but this should be solvable by using either the Baseline Feature or System.Diagnostics.CodeAnalysis.SuppressMessage on assembly level:
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Contracts", "Whatever")]
您可以使用SuppressMessageAttribute的"Target"属性仅忽略特定类型/方法/命名空间上的消息:
You can use the "Target" Property of the SuppressMessageAttribute to only ignore the Message on specific Types / Methods / Namespaces:
[SuppressMessage("Microsoft.Contracts",
"CC1055",
Scope="Member",
Target="YouNamespace.EnvDTE.Project")]
请注意,我使用的参数只是一个不错的选择,您必须找出正确的Scope,MessageId和Target Target :)在一个旁注中,我认为该属性是Conditional("CODE_ANALYSIS").
Note that the Parameters i used are just a good bet, you´ll have to figure out the correct Scope, MessageId and Target yourself :) On a sidenote, i think the Attribute is Conditional("CODE_ANALYSIS").
此问题的官方建议解决方案是创建某种包装器,在您的情况下,可能是一个将创建或包含EnvDTE.Project对象的存储库.然后,您可以添加所需的合同.确保在那里.
The official suggested solution to this problem is to create some sort of wrapper, in your case probably a repository that would create or contain your EnvDTE.Project objects. Then you can add the required Contract.Ensures there.
这篇关于如何使代码合同忽略特定的程序集引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!