Conditional operator doesn't work with two types that inherit the same base type

后端 未结 3 1770
遇见更好的自我
遇见更好的自我 2021-01-11 14:52

How come the conditional operator (?:) doesn\'t work when used with two types that inherit from a single base type?

The example I have is:



        
3条回答
  •  悲&欢浪女
    2021-01-11 15:38

    The conditional part tries to resolve itself regardless of the variable it's being assigned to. The compiler gives a warning that it can't determine which class to use as a return value, because RedirectToRouteResult can't be cast the same as RedirectResult, as far as the conditional part is concerned. However if just one side is cast to the base class, the other is implicitly cast as well, so casting the first would be valid:

     var foo = (someCondition)? 
                      (ActionResult )RedirectToAction("Foo","Bar") :
                      Redirect(someUrl);
    

    but only casting the alternative too:

     var foo = (someCondition)? 
        RedirectToAction("Foo","Bar") :
       (ActionResult)Redirect(someUrl);
    

提交回复
热议问题