ReSharper 2026.3 Help

代码检查:合同注解定义中的问题

此检查会验证 契约注解 的语法。

契约注解的语法

使用以下语法指定合同注解的输入输出依赖关系:

[ContractAnnotation("[paramName:][input] => output [; [paramName:][input] => output]", [forceFullStates:true])]

input 可以是:

  • null/notnull 用于引用类型参数

  • true/false 用于布尔类型参数。

output 可以是

  • null/notnull/canbenull 用于引用类型的返回值

  • true/false 用于布尔类型的返回值

  • halt | stop | void | nothing (它们是可互换的)以指示函数不会正常返回。 也就是说,它会抛出异常或终止程序执行。

The optional boolean forceFullStates parameter, which is false by default, allows you to force the pessimistic mode for the nullability analysis. That is, if the method return value is not defined by the contract condition, ReSharper assumes that it might be null.

言论:

  • 如果只有一个参数,您可以省略 paramName (请参见上面的示例)

  • 如果没有参数,您可以同时省略 paramName 和 input:

    [ContractAnnotation("=> halt")] public void TerminationMethod()

    or if the function has the same output independently of the input:

    [ContractAnnotation("=> halt")] public void TerminationMethod(object data, bool flag)
  • 您可以为同一参数添加多个条件:

    [ContractAnnotation("input:null => null; input:notnull=>notnull")] public object Transform(object input, bool flag)
  • 您可以反转条件,也就是说 input => output 等于 output <= input:

    [ContractAnnotation("null <= surname:null")] public string GetName(string surname)
  • 您还可以为 'out' 参数指定预期值。 如果您想为同一输入条件同时指定返回值和 'out' 参数,请使用逗号:

    [ContractAnnotation("s:null => false,result:null")] public bool TryParse(string s, out object result)
2026年 11月 6日