Skip to content

Commit

Permalink
fix enum cast
Browse files Browse the repository at this point in the history
  • Loading branch information
Takasakiii committed Oct 26, 2023
1 parent f5d017e commit e56af34
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Lina/Lina.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>2.0.0-preview.6</Version>
<Version>2.0.0-preview.8</Version>
<PackageId>TakasakiStudio.Lina</PackageId>
<Authors>TakasakiStudio</Authors>
<RepositoryUrl>https://github.com/Takasaki-Studio/Lina</RepositoryUrl>
Expand Down
25 changes: 22 additions & 3 deletions Lina/UtilsExtensions/EnumExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,31 @@ public static T ToFlags<T>(this IEnumerable<T> list)
where T : struct, Enum
{
var result = 0UL;
var underlyingType = Enum.GetUnderlyingType(typeof(T));
foreach (var flag in list)
{
var flagInNumber = Convert.ToUInt64(flag);
result |= flagInNumber;
var flagInNumber = Convert.ChangeType(flag, underlyingType).ToString();
if (flagInNumber is not null)
{
result |= uint.Parse(flagInNumber);
}
}

return (T)Enum.ToObject(typeof(T), result);
return (T)Enum.ToObject(typeof(T), Convert.ChangeType(result, underlyingType));
}

public static IEnumerable<T> ToEnumerable<T>(this T flag)
where T : struct, Enum
{
var flagInNumber = Convert.ToUInt64(flag);
var underlyingType = Enum.GetUnderlyingType(typeof(T));
return Enum.GetValues<T>()
.Select(x =>
{
var stringConverted = Convert.ChangeType(x, underlyingType).ToString();
return ulong.Parse(stringConverted ?? "0");
})
.Where(x => (x & flagInNumber) == x)
.Select(x => (T)Enum.ToObject(typeof(T), x));
}
}

0 comments on commit e56af34

Please sign in to comment.