c# casting with is and as

后端 未结 5 978
灰色年华
灰色年华 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 are testing for multiple types, then as+null check is more efficient (just one cast, instead of is + casting):

    var a = myObject as ClassA;
    if (a != null)
        a.MethodJustInA();
    var b = myObject as ClassB;
    if (b != null)
        b.MethodJustInB();
    

    In given scenario I'd even make local scope like this

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

    { } make it possible to reuse same variable name (easier to copy/paste and, in my oppinion, read).


    I was a bit rushy and haven't thought well about else case (when myObject is ClassA you don't want to cast it as b, etc.). Normally I'd do return after each successful if and corresponding method call. I am not able to construct nice looking if/else if code otherwise.


    Another idea is to use C# 6.0 null-conditional operator:

    (myObject as ClassA)?.MethodJustInA();
    (myObject as ClassB)?.MethodJustInB();
    

    That looks really neat, but it will do unnecessarily casting to B and has side-effect: if ClassB inherits ClassA, then both methods will be called because both casts will success.

    Note: mentioned side effect unfortunately applies to all proposed snippets.

提交回复
热议问题