Ada*_*dam 9 c# resharper extension-methods code-contracts nullreferenceexception
这是使用Visual Studio 2012的ReSharper 7.下面的示例
// This code works fine and as expected and ReShrper is happy with it
if (!string.IsNullOrWhiteSpace(extension) && extension.Length == 3)
{
// do something
}
// ReSharper highlights "extension" in extension.Length with "Possible 'System.NullReferenceException'"
if (!extension.IsNullOrWhiteSpace() && extension.Length == 3)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
并且,我创建了以下扩展方法:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string s)
{
return string.IsNullOrWhiteSpace(s);
}
}
Run Code Online (Sandbox Code Playgroud)
我查看了反映的代码,String.IsNullOrWhiteSpace
它没有任何相关的代码或属性,这些代码或属性会突出显示R#验证检查.这是硬编码在R#?
我查看了代码合同,但我不确定它会对我的情况有所帮助.
您是否有一种解决方法可以向ReSharper证明我的扩展方法已经验证了检查条件?
wal*_*wal 16
[ContractAnnotation("null=>true")]
public static bool IsNullOrWhiteSpace(this string s)
Run Code Online (Sandbox Code Playgroud)
你的项目不知道是什么ContractAnnotation
.您需要将它添加到您的项目中.首选方法是通过nuget:
PM> Install-Package JetBrains.Annotations
或者,您可以直接将源嵌入到项目中:
Resharper - >选项 - >代码注释 - >将默认实现复制到剪贴板
然后将其粘贴到新文件中,例如Annotations.cs.该ContractAnnotation
定义存在于该文件中.有关ContractAnnotation的官方文章,请参见此处
这是硬编码在R#?
不,Resharper使用外部注释来提供此功能.本文应回答您的所有问题,包括为您的IsNullOrWhiteSpace
方法提供自己的外部注释的解决方案.
注意:外部注释似乎仅适用于引用的库; 如果您的参考来自项目,则不会选择外部注释; 这不太理想
假设您在一个类中有您的扩展方法,该类TempExtensions
本身位于一个名为的程序集中ClassLibrary1
您需要在此位置添加新文件
C:\ Program Files(x86)\ JetBrains\ReSharper\v7.0\Bin\ExternalAnnotations.NETFramework.ExternalAnnotations\ClassLibrary1\ClassLibrary1.xml
xml的内容应包含:
<assembly name="ClassLibrary1">
<member name="M:ClassLibrary1.TempExtensions.IsNullOrWhiteSpace(System.String)">
<attribute ctor="M:JetBrains.Annotations.ContractAnnotationAttribute.#ctor(System.String,System.Boolean)">
<argument>null=>true</argument>
<argument>true</argument>
</attribute>
</member>
</assembly>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1862 次 |
最近记录: |