c# casting with is and as

后端 未结 5 1039
灰色年华
灰色年华 2021-01-27 13:48

I need some help. It is pretty easy. I have this piece of code, and I would like to discuss if it is correct, or if you suggest a better way to do it. I have an idea about the a

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 14:04

    I prefer to cast with as and then check for null, this way you can skip the is check. Also, you do not need the elvis operator ?. because you know the object is not null.

    var myObjectA = myObject as ClassA;
    var myObjectB = myObject as ClassB;
    if (myObjectA != null)
    {
        myObjectA.MethodJustInA();
    }
    else if (myObjectB != null)
    {
        myObjectB.MethodJustInB();
        myObjectB.OtherMethodJustInB();
    }
    

提交回复
热议问题