The enum has a backing store, defaulting to int if you don't specify it. It is possible to directly assign values outside of the defined values:
Sport pingPong = (Sport)4;
Then you can check for it:
if (value == (Sport)4) {}
That is why you have the static function Enum.IsDefined()
for checking if the actual value falls inside the expected values. Note that the function doesn't work for compound flag values.
bool isValueDefined = Enum.IsDefined(typeof(Sport), value);
EDIT: After Hans Passant's comment: You don't have to use the literal value 4. You could use anything which returns an int. For example:
Dictionary<int, string> AdditionalSports = new Dictionary<int, string>();
AdditionalSports.Add(4, "PingPong");
// Usages: if
if (AdditionalSports.ContainsKey(value))
{
// Maybe do something with AdditionalSports[value], i.e. "PingPong"
}
// In a switch:
switch (value)
{
case default:
// Since it won't be found in the enum-defined values
if (AdditionalSports.ContainsKey(value))
{
// Maybe do something with AdditionalSports[value], i.e. "PingPong"
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…