且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确定是否枚举值列表中(C#)

更新时间:2023-02-22 12:03:22

您当前的code会说,无论是的完全的雨及雷暴。要找出无论是雨及雷暴,可能别的东西,你需要:

  IF((currentWeather.Type&安培; _badWeatherTypes)== _badWeatherTypes)
 

要找出是否是下雨的的雷雨,并可能别的东西,你需要:

  IF((currentWeather.Type&安培;!_badWeatherTypes)= 0)
 

Edit(对于完整性):

这将是很好的使用的FlagsAttribute ,即装点着类型[国旗] 。这是没有必要为了这个按位逻辑,但会影响的ToString()的行为。 C#编译器会忽略这个属性(至少在目前,在C#3.0规范并没有提到它),但它通常用于枚举它们是有效的标志是一个好主意,它记录了预定用途的类型。与此同时,该约定是,当你使用的标志,你pluralise枚举名字 - 所以你***将它更改为 WeatherTypes (因为任何实际值有效0或更多天气类型)。

这也将是值得我们思考什么是阳光的真正含义。目前它有一个值为0,这意味着它是没有一切都黯然失色。你不能把它晴天下雨的同时(这当然是实际可能,)。请不要写code禁止彩虹! ;)在另一方面,如果在你的实际使用情况,你真心希望的值,这意味着不存在的所有其他值,那么你的罚款

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).

public enum WeatherType : byte
{ Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 }

I was thinking I could do something like:

WeatherType _badWeatherTypes = WeatherType.Thunderstorm | WeatherType.Raining;
if(currentWeather.Type == _badWeatherTypes)
{
 return false;//don't bike
}

but this doesn't work because _badWeatherTypes is a combination of both types. I would like to keep them separated out because this is supposed to be a learning experience and having it separate may be useful in other situations (IE, Invoice not paid reason's etc...).

I would also rather not do: (this would remove the ability to be configured for multiple people)

if(WeatherType.Thunderstorm)
{
 return false; //don't bike
}
etc...

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.