Bud*_*dda 11 .net c# resharper configuration nullreferenceexception
这是一段代码:
IUser user = managerUser.GetUserById(UserId);
if ( user==null )
throw new Exception(...);
Quote quote = new Quote(user.FullName, user.Email);
Run Code Online (Sandbox Code Playgroud)
这里一切都很好.但是,如果我用以下内容替换"if"行:
ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);
Run Code Online (Sandbox Code Playgroud)
函数实现如下:
public abstract class ComponentException<T> : ComponentException
where T : ComponentException, new()
{
public static void FailIfTrue(bool expression, string message)
{
if (expression)
{
T t = new T();
t.SetErrorMessage(message);
throw t;
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
然后resharper生成一个警告:可能'System.NullReferenceException'指向'user'对象的第一次使用.
Q1.为什么会产生这种异常?据我所知,如果'user == null',那么将生成异常并且执行将永远不会到达使用点.
Q2.如何删除该警告?请注意:1.我不想用注释来抑制此警告(我将有很多类似的部分,并且不想在'评论的garbase中转换我的源代码); 2.我不想更改resharper设置以将此问题从警告更改为"提示"的"建议".
谢谢.
欢迎任何想法!
PS我正在使用resharper 5.1,MVSV 2008,C#
小智 6
旧帖子中的新答案......
这里有一些关于如何通过ContractAnnotation与Resharper一起使用CodeContract的代码示例:
[ContractAnnotation("value:null=>true")]
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
Run Code Online (Sandbox Code Playgroud)
这很简单......如果你在木头上发现了面包屑.您也可以查看其他案例.
祝你今天愉快
| 归档时间: |
|
| 查看次数: |
13728 次 |
| 最近记录: |