'is' versus try cast with null check

后端 未结 7 605
情歌与酒
情歌与酒 2020-12-08 03:28

I noticed that Resharper suggests that I turn this:

if (myObj.myProp is MyType)
{
   ...
}

into this:

var myObjRef = myObj.         


        
相关标签:
7条回答
  • 2020-12-08 04:25

    Resharper warning:

    "Type check and direct cast can be replaced with try cast and check for null"

    Both will work, it depends how your code suits you more. In my case I just ignore that warning:

    //1st way is n+1 times of casting
    if (x is A) ((A)x).Run();
    else if (x is B) ((B)x).Run();
    else if (x is C) ((C)x).Run();
    else if (x is D) ((D)x).Run();
    //...
    else if (x is N) ((N)x).Run();    
    //...
    else if (x is Z) ((Z)x).Run();
    
    //2nd way is z times of casting
    var a = x as Type A;
    var b = x as Type B;
    var c = x as Type C;
    //..
    var n = x as Type N;
    //..
    var z = x as Type Z;
    if (a != null) a.Run();
    elseif (b != null) b.Run();
    elseif (c != null) c.Run();
    ...
    elseif (n != null) n.Run();
    ...
    elseif (x != null) x.Run();
    

    In my code 2nd way is longer and worse performance.

    0 讨论(0)
提交回复
热议问题