Direct casting vs 'as' operator?

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

提交回复
热议问题