Skip to content

Commit 413c90d

Browse files
Added more flexible initializing options for the CacheInitializer
1 parent 007c3e6 commit 413c90d

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

src/StringyEnums/StringyEnums/CacheInitializer.cs

+27-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using BidirectionalDict;
1+
using BidirectionalDict;
22
using System;
33
using System.Collections.Generic;
44
using System.Collections.ObjectModel;
@@ -31,33 +31,42 @@ public CacheInitializer InitWith(params Assembly[] assemblies)
3131

3232
foreach (var enumType in enumTypes)
3333
{
34-
var fields = enumType.GetFields();
34+
InitWith(enumType);
35+
}
36+
}
3537

36-
var temptDict = new BiDictionary<int, string>();
38+
return this;
39+
}
3740

38-
foreach (var field in fields.Where(x => x.IsStatic))
39-
{
40-
var attr = field.GetCustomAttribute<StringRepresentationAttribute>();
41+
/// <summary>
42+
/// Initializes the cache with a given enum.
43+
/// </summary>
44+
/// <typeparam name="TEnum">The enum which should be added to the cache.</typeparam>
45+
public CacheInitializer InitWith<TEnum>() where TEnum : struct, Enum
46+
{
47+
InitWith(typeof(TEnum));
4148

42-
if (attr is { })
43-
{
44-
temptDict.TryAdd((int)field.GetValue(enumType)!, attr.StringRepresentation);
45-
}
46-
}
49+
return this;
50+
}
4751

48-
if (temptDict.Count > 0)
49-
{
50-
_tempCache.Add(enumType, temptDict);
51-
}
52-
}
52+
/// <summary>
53+
/// Initializes the cache with a set of given enums.
54+
/// </summary>
55+
/// <param name="enums">The enums which should be added to the cache.</param>
56+
public CacheInitializer InitWith(params Enum[] enums)
57+
{
58+
foreach (var enumVal in enums)
59+
{
60+
InitWith(enumVal);
5361
}
5462

5563
return this;
5664
}
5765

58-
public CacheInitializer InitWith<TEnum>() where TEnum : struct, Enum
66+
private void InitWith(Type enumType)
5967
{
60-
var enumType = typeof(TEnum);
68+
if (!enumType.IsEnum)
69+
throw new ArgumentException("The type provided is not of type enum", nameof(enumType));
6170

6271
var fields = enumType.GetFields();
6372

@@ -77,8 +86,6 @@ public CacheInitializer InitWith<TEnum>() where TEnum : struct, Enum
7786
{
7887
_tempCache.Add(enumType, temptDict);
7988
}
80-
81-
return this;
8289
}
8390

8491
internal IReadOnlyDictionary<Type, IReadOnlyBiDictionary<int, string>> CustructCache()

0 commit comments

Comments
 (0)