Direct casting vs 'as' operator?

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

    2 is useful for casting to a derived type.

    Suppose a is an Animal:

    b = a as Badger;
    c = a as Cow;
    
    if (b != null)
       b.EatSnails();
    else if (c != null)
       c.EatGrass();
    

    will get a fed with a minimum of casts.

提交回复
热议问题