Hallo ich habe ein Problem, ich habe ein Enum:
enum FontStyle
{
Regular = 0,
Bold = 1,
Italic = 2,
Underline = 4,
Strikeout = 8,
}
FontStyle style1 = FontStyle.Regular;
FontStyle style2 = FontStyle.Bold | FontStyle.Strikeout;
Jetzt möchte ich überprüfen ob in style2 ein Bold drin steckt oder nich.
Was währe die einfachste lösung?
Hallo lord_fritte,
if ((style2 & FontStyle.Bold)>0) {}
oder auch
if ((style2 & FontStyle.Bold) == FontStyle.Bold) {}
Gruß,
dN!3L
Hallo ich habe ein Problem, ich habe ein Enum
Der ist gut... 😉
Zusätzlich musst du deinem Enum noch das Flags-Attribute verpassen.
Es gibt 3 Arten von Menschen, die die bis 3 zählen können und die, die es nicht können...
Hallo kleines_eichhoernchen,
muss nicht, sollte.
herbivore
Kann man so eine Kombination auch wieder auflösen dass ich aus FontStyle.Bold | FontStyle.Strikeout ein array von FontStyle bekomme?
Hallo lord_fritte,
was fertiges gibt es wohl nicht, aber das kannst du ja leicht selbst programmieren (for, <≤, &, ==). Siehe auch [Artikel] Bitoperationen in C#.
herbivore
Hallo lord_fritte,
Du könntest diesen Ansatz anschauen/erweitern:
static T[] Factorize<T>(T value) where T : struct
{
Type type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException("value");
List<T> result = new List<T>(64);
ulong bitField = Convert.ToUInt64(value);
ulong bit = 1;
for (int i = 0; i < 64; i++, bit <<= 1)
{
ulong u = (bitField & bit);
if (u != 0)
{
result.Add((T)Enum.ToObject(type, u));
}
}
return result.ToArray();
}
Spooky