-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathSmartEnumValueResolver.cs
44 lines (39 loc) · 1.3 KB
/
SmartEnumValueResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace Ardalis.SmartEnum.Utf8Json
{
using System;
using global::Utf8Json;
/// <summary>
///
/// </summary>
public class SmartEnumValueResolver : IJsonFormatterResolver
{
/// <summary>
///
/// </summary>
public static readonly SmartEnumValueResolver Instance = new SmartEnumValueResolver();
private SmartEnumValueResolver()
{
}
/// <summary>
/// GetFormatter
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IJsonFormatter<T> GetFormatter<T>() =>
FormatterCache<T>.Formatter;
private static class FormatterCache<T>
{
public static readonly IJsonFormatter<T> Formatter;
#pragma warning disable S3963 // "static" fields should be initialized inline
static FormatterCache()
{
if (typeof(T).IsSmartEnum(out var genericArguments))
{
var formatterType = typeof(SmartEnumValueFormatter<,>).MakeGenericType(genericArguments);
Formatter = (IJsonFormatter<T>)Activator.CreateInstance(formatterType);
}
}
#pragma warning restore S3963 // "static" fields should be initialized inline
}
}
}