c# casting with is and as

后端 未结 5 984
灰色年华
灰色年华 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:08

    There are some optimizations possible.

    • If myObject is ClassA, you don't need the soft cast. Instead you can do the cast directly: var myObjectA = (ClassA)myObject;.
    • Since that is the case, and you just call a single method, you don't need to assign a new variable: ((ClassA)myObject)?.MethodJustInA();.
    • And because myObject is ClassA evaluates to false if myObject is null, you don't need to do the check again: ((ClassA)myObject).MethodJustInA();.

    So:

    if (myObject is ClassA)
    {
        ((ClassA)myObject).MethodJustInA();
    }
    else if (myObject is ClassB)
    {
        var myObjectB = (ClassB)myObject;
        myObjectB.MethodJustInB();
        myObjectB.OtherMethodJustInB();
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题