Direct casting vs 'as' operator?

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

    1. string s = (string)o; Use when something should definitely be the other thing.
    2. string s = o as string; Use when something might be the other thing.
    3. string s = o.ToString(); Use when you don't care what it is but you just want to use the available string representation.

提交回复
热议问题