-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
EnumConverterFactory.cs
36 lines (30 loc) · 1.66 KB
/
EnumConverterFactory.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
namespace System.Text.Json.Serialization.Converters
{
[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
internal sealed class EnumConverterFactory : JsonConverterFactory
{
public EnumConverterFactory()
{
}
public override bool CanConvert(Type type)
{
return type.IsEnum;
}
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
=> Create(type, EnumConverterOptions.AllowNumbers, namingPolicy: null, options);
internal static JsonConverter Create(Type enumType, EnumConverterOptions converterOptions, JsonNamingPolicy? namingPolicy, JsonSerializerOptions options)
{
return (JsonConverter)Activator.CreateInstance(
GetEnumConverterType(enumType),
new object?[] { converterOptions, namingPolicy, options })!;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "'EnumConverter<T> where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because enumType's constructors are not annotated. " +
"But EnumConverter doesn't call new T(), so this is safe.")]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
private static Type GetEnumConverterType(Type enumType) => typeof(EnumConverter<>).MakeGenericType(enumType);
}
}