簡體   English   中英

C#中的空解除引用控制

[英]Null dereference control in c#

經過一些有關“空取消引用”的測試后,下面的代碼可以“取消引用空指針,從而引發NullException”。

if((validateControl as WebControl) != null)
    (validateControl as WebControl).CssClass (IsValid) ? "stack" : "overflow";

可以將(validateControl as WebControl).CssClass與上述使用為null嗎?

結果可以在Fortify生成的文檔中看到。

如果不是WebControl false ,否則為true

bool isWebControl = validateControl is WebControl;

如果不是WebControlWebControl null ,否則為WebControl

WebControl webControl = validateControl as WebControl;

(validateControl as WebControl)可以為null嗎?

是的,每次使用as ,理論上結果都可能為空。 代碼分析工具看不到您剛剛檢查了它是否不為null,並且仍然假設as的下一次使用可能為null。 因此,您應該將其放在變量中,並改用它:

WebControl webControl = validateControl as WebControl;
if (webControl != null)
{
    // Here 'webControl' is surely _not_ null.
    webControl.CssClass = Page.IsValid ? "stack" : "overflow";
}

(validateControl as WebControl).CssClass可以為空嗎?

您從CssClass獲得的值可能為null。 但是由於CssClass是屬性,因此只要validateControlWebControl ,該屬性將始終存在。

重新格式化代碼以使其更加明確。

var webControl = validateControl as WebControl;
if(webControl != null)
{
    var cssClass = IsValid ? "stack" : "overflow";
    webControl.CssClass = cssClass;
}

是的,可以。 如果很重要,一旦知道validateControl不為null且為WebControl,則根據“ valid”的含義對CssClass進行可空性測試,並可能為空或僅空白

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM