Direct casting vs 'as' operator?

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:10

    I would like to attract attention to the following specifics of the as operator:

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

    Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

    0 讨论(0)
  • 2020-11-22 02:13

    According to experiments run on this page: http://www.dotnetguru2.org/sebastienros/index.php/2006/02/24/cast_vs_as

    (this page is having some "illegal referrer" errors show up sometimes, so just refresh if it does)

    Conclusion is, the "as" operator is normally faster than a cast. Sometimes by many times faster, sometimes just barely faster.

    I peronsonally thing "as" is also more readable.

    So, since it is both faster and "safer" (wont throw exception), and possibly easier to read, I recommend using "as" all the time.

    0 讨论(0)
  • 2020-11-22 02:13
    string s = o as string; // 2
    

    Is prefered, as it avoids the performance penalty of double casting.

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题