Direct casting vs 'as' operator?

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

    Use direct cast string s = (string) o; if in the logical context of your app string is the only valid type. With this approach, you will get InvalidCastException and implement the principle of Fail-fast. Your logic will be protected from passing the invalid type further or get NullReferenceException if used as operator.

    If the logic expects several different types cast string s = o as string; and check it on null or use is operator.

    New cool feature have appeared in C# 7.0 to simplify cast and check is a Pattern matching:

    if(o is string s)
    {
      // Use string variable s
    }
    
    or
    
    switch (o)
    {
      case int i:
         // Use int variable i
         break;
      case string s:
         // Use string variable s
         break;
     }
    

提交回复
热议问题