3

I have several user controls, that are subscribed to the event handler in another class. I'm learning CodeContracts in C#, and I wonder, why does Static Analyzer allows writing code like this:

void MyUserControl_MouseEnter(object sender, MouseEventArgs e)
{
  MyUserControl item = sender as MyUserControl;      
  item.DoSomething(); // I expect some warning here, because item can be null

  sender.Equals(testObject); // This doesn't yield warning either 
}

Here I have a potentially unsafe code, that can lead to null-reference exception. I understand, that static analyzer probably cannot check, what will the actual type of sender be. But in case it cannot prove it, I expect some warning, like CodeContracts: Possibly calling a method on a null reference.

Or do I get some idea of contracts wrong? How can I get notified of errors like this?

UPD:

Yes, I did enable Implicit Non-Null Obligation as it was suggested in the answers, but I still don't get a warning from Static Analyzer. Also I tried to run Code Analysis with Microsoft All Rules rules set, also no warning. (But I'd prefer dealing with Code Contracts and perform some additional checks using Contract class, rather then with if-then-throw or something else)

4

4 回答 4

3

您应该在静态分析器选项(项目选项|代码分析)中启用“隐式非空义务”。

于 2011-11-18T18:48:37.173 回答
0

我有一个类似的问题。我不得不在与“隐式非空义务”复选框相同的面板上打开警告级别滑块。

于 2013-03-01T00:57:56.700 回答
0

“我怎样才能得到这样的错误通知?”:在这种情况下,Resharper 会警告你。

如果“要求”对象为非空,代码合同将警告您该对象可能为空。您要求对象取消引用的隐式“要求”,从表面上看这似乎是合理的,但无论出于何种原因,CC 似乎都没有提供。

http://msdn.microsoft.com/en-us/library/dd264808.aspx上的文档说它确实执行了这样的隐式合同。我正在进一步调查。

RedHat 打败了我。更多详细信息:您应该在项目属性的代码合同选项卡中选中“静态检查”下的“隐式非空义务”框。

于 2011-11-18T18:43:21.110 回答
-1

代码分析选项卡上项目的属性页面中,您可以更改规则

于 2011-11-18T18:47:01.213 回答