SA1125:为什么强制执行“int?”而不是“Nullable <int>”而不是“typeof()”?</int>

时间:2013-04-22 11:33:05

标签: c# stylecop

SA1125:UseShorthandForNullableTypes具有此描述(取自StyleCop 4.7设置编辑器应用程序):

  

强制使用可空类型的简写而不是Nullable<T>typeof()内的typeof()

是否有typeof(int?)声明例外的原因? var x = new Nullable<int>(); var y = new int?(); var z = typeof(Nullable<int>); var v = typeof(int?); 编译同样合适 - 这只是StyleCop作者的偏好还是有更深层次的推理?

编辑:由于官方文档没有提及此例外,我测试了以下代码:

{{1}}

结果:只有第一行引发SA1125警告。

修改2 The work item for StyleCop asking to fix this behavior

2 个答案:

答案 0 :(得分:3)

虽然我实际上并不知道原因(因为我不是此规则的开发人员),但我怀疑它是以这种方式设计的,不会针对typeof的特定用法生成警告:

typeof(Nullable<>)

话虽如此,如果这是实际的官方原因,他们可以硬编码此特定用法的例外,而不是为typeof(Nullable<X>)的所有用法编写例外。

请注意,所有这些只是假设


EDIT 来自source code of Stylecop

// Check the declaration of the generic type for longhand, but allow Nullable<> which has no shorthand

所以从我的理解,基本上搜索longhand泛型类型,并处理它们允许的Nullable<>的特殊情况,因为没有可用的简写。 AFAIK,Nullable<>只在typeof()的上下文中有意义,所以我猜他们在这种情况下做了例外。

答案 1 :(得分:0)

我的观点是,这至多是一个错误,至少是一个错过的行为。代码说明:

// Check the declaration of the generic type for longhand, but allow Nullable<> which has no shorthand
if (genericType.ChildTokens.Count > 0 && Utils.TokenContainNullable(genericType.ChildTokens.First))
{
    if (genericType.Parent == null || !(genericType.Parent is TypeofExpression))
    {

它似乎试图支持Nullable<>内的typeof(Nullable<>)。但是,TypeofExpression上的检查无意中过滤掉了已关闭的泛型。

寻找CheckShorthandForNullableTypes

http://stylecop.codeplex.com/SourceControl/changeset/view/249eed5b15ed#Project/Src/AddIns/CSharp/Analyzers/ReadabilityRules.cs