[英]Null dereference control in c#
After some testing which is about "null dereference", below code can "dereference a null pointer, thereby raising a NullException". 经过一些有关“空取消引用”的测试后,下面的代码可以“取消引用空指针,从而引发NullException”。
if((validateControl as WebControl) != null)
(validateControl as WebControl).CssClass (IsValid) ? "stack" : "overflow";
Can (validateControl as WebControl).CssClass be null with above using? 可以将(validateControl as WebControl).CssClass与上述使用为null吗?
The result is seen in document which is produced by Fortify. 结果可以在Fortify生成的文档中看到。
To get false
when it's not a WebControl
, and true
otherwise: 如果不是
WebControl
false
,否则为true
:
bool isWebControl = validateControl is WebControl;
To get null
when it's not a WebControl
, and a WebControl
otherwise: 如果不是
WebControl
, WebControl
null
,否则为WebControl
:
WebControl webControl = validateControl as WebControl;
(validateControl as WebControl)
be null? (validateControl as WebControl)
可以为null吗? Yes, every time you use as
, the result could be null in theory. 是的,每次使用
as
,理论上结果都可能为空。 Code analysis tools don't see that you just checked that it is not null, and will still assume the next use of as
is possibly null. 代码分析工具看不到您刚刚检查了它是否不为null,并且仍然假设
as
的下一次使用可能为null。 So you should put it in a variable and use that instead: 因此,您应该将其放在变量中,并改用它:
WebControl webControl = validateControl as WebControl;
if (webControl != null)
{
// Here 'webControl' is surely _not_ null.
webControl.CssClass = Page.IsValid ? "stack" : "overflow";
}
(validateControl as WebControl).CssClass
be null? (validateControl as WebControl).CssClass
可以为空吗? The value you get from CssClass
might be null. 您从
CssClass
获得的值可能为null。 But since CssClass
is a property, the property will always be there as long as validateControl
is a WebControl
. 但是由于
CssClass
是属性,因此只要validateControl
是WebControl
,该属性将始终存在。
How about reformatting your code to be more explicit. 重新格式化代码以使其更加明确。
var webControl = validateControl as WebControl;
if(webControl != null)
{
var cssClass = IsValid ? "stack" : "overflow";
webControl.CssClass = cssClass;
}
Yes it could. 是的,可以。 If it matters, once you know validateControl is not null and is a WebControl, then you test CssClass for nullability and possibly empty or just whitespace depending on what "valid" means
如果很重要,一旦知道validateControl不为null且为WebControl,则根据“ valid”的含义对CssClass进行可空性测试,并可能为空或仅空白
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.