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警告。
答案 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
: