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

Обновлено: 27.03.2025

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

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
10 ч 44 мин назад
7 минут и морщины исчезли. Вот что спасет вашу кожу от старения

Еще

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
4 ч 0 мин назад
Стальная потенция будет всю ночь! Вот что нужно сделать вечером

Еще

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
3 ч 32 мин назад
Кардиолог шокировал мировую медицину: сосуды чистит простой...

Еще

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
2 мин назад
Позвали Таню, и жены начали уводить мужей. Не стесняется стыдобы

Еще

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
11 ч 26 мин назад
Не смейте выбрасывать зажимы от хлебных упаковок: они бесценны

Еще

Реклама
  • ИП Попов А.П.
  • ИНН: 602715631406
block-axgp4hfecu7img
1 ч 2 мин назад
Надоели боли в суставах? 7 дней и ваши суставы восстановятся

Еще

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