Direct casting vs 'as' operator?

后端 未结 16 1813
独厮守ぢ
独厮守ぢ 2020-11-22 01:43

Consider the following code:

void Handler(object o, EventArgs e)
{
   // I swear o is a string
   string s = (string)o; // 1
   //-OR-
   string s = o as str         


        
16条回答
  •  有刺的猬
    2020-11-22 01:57

    The as keyword is good in asp.net when you use the FindControl method.

    Hyperlink link = this.FindControl("linkid") as Hyperlink;
    if (link != null)
    {
         ...
    }
    

    This means you can operate on the typed variable rather then having to then cast it from object like you would with a direct cast:

    object linkObj = this.FindControl("linkid");
    if (link != null)
    {
         Hyperlink link = (Hyperlink)linkObj;
    }
    

    It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable

提交回复
热议问题