Direct casting vs 'as' operator?

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

    'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basically if a cast can be made) and returns null if the check fails.

    These two are equivalent:

    Using 'as':

    string s = o as string;
    

    Using 'is':

    if(o is string) 
        s = o;
    else
        s = null;
    

    On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.

    Just to add an important fact:

    The 'as' keyword only works with reference types. You cannot do:

    // I swear i is an int
    int number = i as int;
    

    In those cases you have to use casting.

提交回复
热议问题