Direct casting vs 'as' operator?

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

    If you already know what type it can cast to, use a C-style cast:

    var o = (string) iKnowThisIsAString; 
    

    Note that only with a C-style cast can you perform explicit type coercion.

    If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:

    var s = o as string;
    if (s != null) return s.Replace("_","-");
    
    //or for early return:
    if (s==null) return;
    

    Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.

    Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.

提交回复
热议问题