-
Notifications
You must be signed in to change notification settings - Fork 0
/
typeConverter.mustache
42 lines (39 loc) · 1.29 KB
/
typeConverter.mustache
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
using System;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace {{packageName}}.Converters
{
/// <summary>
/// Custom string to enum converter
/// </summary>
public class CustomEnumConverter<T> : TypeConverter
{
/// <summary>
/// Determine if we can convert a type to an enum
/// </summary>
/// <param name="context"></param>
/// <param name="sourceType"></param>
/// <returns></returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Convert from a type value to an enum
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return null;
}
return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
}
}
}