Direct casting vs 'as' operator?

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

    When trying to get the string representation of anything (of any type) that could potentially be null, I prefer the below line of code. It's compact, it invokes ToString(), and it correctly handles nulls. If o is null, s will contain String.Empty.

    String s = String.Concat(o);
    

提交回复
热议问题