BizSourceHelper.cs
1.47 KB
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
45
46
47
using System;
using System.ComponentModel;
using System.Reflection;
namespace NCC.Extend
{
/// <summary>
/// 开单/耗卡来源校验。只接受枚举 Description 中的中文值。
/// </summary>
public static class BizSourceHelper
{
/// <summary>
/// 校验来源,合法时返回中文标签。
/// </summary>
public static bool TryResolve<TEnum>(string raw, out string label) where TEnum : struct, Enum
{
label = null;
var text = (raw ?? string.Empty).Trim();
if (text.Length == 0)
{
return false;
}
foreach (var value in Enum.GetValues(typeof(TEnum)))
{
var field = typeof(TEnum).GetField(value.ToString());
var desc = field?.GetCustomAttribute<DescriptionAttribute>()?.Description;
if (!string.IsNullOrEmpty(desc) && string.Equals(desc, text, StringComparison.Ordinal))
{
label = desc;
return true;
}
}
return false;
}
/// <summary>
/// 取枚举上的中文标签
/// </summary>
public static string Label<TEnum>(TEnum value) where TEnum : struct, Enum
{
var field = typeof(TEnum).GetField(value.ToString());
return field?.GetCustomAttribute<DescriptionAttribute>()?.Description ?? value.ToString();
}
}
}