Autor Beitrag
erfahrener Neuling
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 233
Erhaltene Danke: 19

Win 7, Win 10
C#, ASP-MVC (VS 2017 Community), MS SQL, Firebird SQL
BeitragVerfasst: Fr 05.08.16 14:13 
Hallo,

wie kann ich einen string mit enum-Werten in einem switch vergleichen?

so geht's nicht:
ausblenden C#-Quelltext
1:
2:
3:
switch(myString)
{
    case MyEnum.ABC.ToString():  //erkennt's nicht als Konstante

Geht das überhaupt?

Danke und Grüße
Julian


Zuletzt bearbeitet von erfahrener Neuling am Fr 05.08.16 14:52, insgesamt 1-mal bearbeitet
Ralf Jansen
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 4700
Erhaltene Danke: 991


VS2010 Pro, VS2012 Pro, VS2013 Pro, VS2015 Pro, Delphi 7 Pro
BeitragVerfasst: Fr 05.08.16 14:28 
Indem du erst aus dem string den Enum machst und dann im switch mit den Enums vergleichst.

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
switch((MyEnum)Enum.Parse(typeof(MyEnum), myString))
{
    case MyEnum.ABC:
    ...
}

Für diesen Beitrag haben gedankt: erfahrener Neuling
erfahrener Neuling Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 233
Erhaltene Danke: 19

Win 7, Win 10
C#, ASP-MVC (VS 2017 Community), MS SQL, Firebird SQL
BeitragVerfasst: Fr 05.08.16 14:52 
Danke so geht's.

Eine Frage noch: Warum gings denn nicht mit .ToString()? Kommt doch eigntl auch n string dabei raus..

EDIT: Ok weil switch nur konstante Werte akzeptiert :/
Ralf Jansen
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 4700
Erhaltene Danke: 991


VS2010 Pro, VS2012 Pro, VS2013 Pro, VS2015 Pro, Delphi 7 Pro
BeitragVerfasst: Fr 05.08.16 14:58 
Zitat:
Eine Frage noch: Warum gings denn nicht mit .ToString()? Kommt doch eigntl auch n string dabei raus..


Aber erst zur Laufzeit die case Zweige eines switches sollten aber zur Compilezeit feststehen.