📅  最后修改于: 2022-03-11 14:59:27.157000             🧑  作者: Mango
public static class EnumExtensions
{
///
/// Gets all items for an enum value.
///
///
/// The value.
///
public static IEnumerable GetAllItems(this Enum value)
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all items for an enum type.
///
///
/// The value.
///
public static IEnumerable GetAllItems() where T : struct
{
foreach (object item in Enum.GetValues(typeof(T)))
{
yield return (T)item;
}
}
///
/// Gets all combined items from an enum value.
///
///
/// The value.
///
///
/// Displays ValueA and ValueB.
///
/// EnumExample dummy = EnumExample.Combi;
/// foreach (var item in dummy.GetAllSelectedItems())
/// {
/// Console.WriteLine(item);
/// }
///
///
public static IEnumerable GetAllSelectedItems(this Enum value)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
foreach (object item in Enum.GetValues(typeof(T)))
{
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);
if (itemAsInt == (valueAsInt & itemAsInt))
{
yield return (T)item;
}
}
}
///
/// Determines whether the enum value contains a specific value.
///
/// The value.
/// The request.
///
/// true if value contains the specified value; otherwise, false .
///
///
///
/// EnumExample dummy = EnumExample.Combi;
/// if (dummy.Contains(EnumExample.ValueA))
/// {
/// Console.WriteLine("dummy contains EnumExample.ValueA");
/// }
///
///
public static bool Contains(this Enum value, T request)
{
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);
if (requestAsInt == (valueAsInt & requestAsInt))
{
return true;
}
return false;
}
}