Determining if enum value is in list (C#)

后端 未结 6 2348
抹茶落季
抹茶落季 2021-01-02 12:32

I am building a fun little app to determine if I should bike to work.

I would like to test to see if it is either Raining or Thunderstorm(ing).

publi         


        
6条回答
  •  渐次进展
    2021-01-02 13:19

    Your current code will say whether it's exactly "raining and thundery". To find out whether it's "raining and thundery and possibly something else" you need:

    if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes)
    

    To find out whether it's "raining or thundery, and possibly something else" you need:

    if ((currentWeather.Type & _badWeatherTypes) != 0)
    

    EDIT (for completeness):

    It would be good to use the FlagsAttribute, i.e. decorate the type with [Flags]. This is not necessary for the sake of this bitwise logic, but affects how ToString() behaves. The C# compiler ignores this attribute (at least at the moment; the C# 3.0 spec doesn't mention it) but it's generally a good idea for enums which are effectively flags, and it documents the intended use of the type. At the same time, the convention is that when you use flags, you pluralise the enum name - so you'd change it to WeatherTypes (because any actual value is effectively 0 or more weather types).

    It would also be worth thinking about what "Sunny" really means. It's currently got a value of 0, which means it's the absence of everything else; you couldn't have it sunny and raining at the same time (which is physically possible, of course). Please don't write code to prohibit rainbows! ;) On the other hand, if in your real use case you genuinely want a value which means "the absence of all other values" then you're fine.

提交回复
热议问题