6

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

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

它有typeof()声明例外的原因吗?typeof(int?)编译一样好 - 这只是 StyleCop 作者的偏好还是有更深层次的推理?

编辑:由于官方文档没有提到这个异常,我测试了以下代码:

var x = new Nullable<int>();
var y = new int?();
var z = typeof(Nullable<int>);
var v = typeof(int?);

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

编辑 2StyleCop 的工作项要求修复此行为

4

2 回答 2

3

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

typeof(Nullable<>)

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

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


编辑来自Stylecop 的源代码

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

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

于 2013-04-22T11:52:03.137 回答
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

于 2013-04-22T12:43:48.530 回答