Direct casting vs 'as' operator?

后端 未结 16 2057
独厮守ぢ
独厮守ぢ 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 02:02

    All given answers are good, if i might add something: To directly use string's methods and properties (e.g. ToLower) you can't write:

    (string)o.ToLower(); // won't compile
    

    you can only write:

    ((string)o).ToLower();
    

    but you could write instead:

    (o as string).ToLower();
    

    The as option is more readable (at least to my opinion).

提交回复
热议问题