c# casting with is and as

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

    If you're using it this way, you only need to cast it ones:

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

    And in C# 7.0 you can do:

    if (myObject is ClassA myObjectA)
        myObjectA.MethodJustInA();
    else 
        if (myObject is ClassB myObjectB)
            myObjectB.MethodJustInB();
    

提交回复
热议问题