Cs8506 не удалось найти лучший тип для выражения switch

Обновлено: 22.12.2024

I have created a running example in sharplab. if switch expression contains the string or other objects it runs fine.

working example 1:

working example 2:

Error example:

original problem (needs fixing):

Thanks to Pavel and Marc, below is the fix:

Follow

18.7k 12 12 gold badges 35 35 silver badges 49 49 bronze badges asked Apr 2 '20 at 13:59 Kamran Pervaiz Kamran Pervaiz 1,711 3 3 gold badges 18 18 silver badges 41 41 bronze badges It would work if Handler1 and Handler2 had a common base type/interface. Apr 2 '20 at 14:01 Apr 2 '20 at 14:01 do MyHandler1 and MyHandler2 share a common base type? perhaps use that instead of var Apr 2 '20 at 14:01 @MarcGravell yes they both have baseType and interface. in sharplab I used BaseHandler/Ihandler it fixes the problem but when I apply same changes in startup DI class it still gives error. Apr 2 '20 at 14:09 maybe return (IHandler) key switch. ? Apr 2 '20 at 14:22

3 Answers 3

You should explicitly declare a type of handler, instead of var

In your sharplab sample both handlers implement IHandler interface and inherit BaseHandler class, compiler simply doesn't know which type to use, you should tell it him explicitly

The same is true for the dependency injection sample, you should explicitly declare a type (assuming that Handler1 and Handler2 implement IHandler )

You can do it only for one constant, compiler is smart enough to do the rest of job for you

Читайте также: