Extends.cs
2.38 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HHECS.Model
{
public static class Extends
{
#region Enum
/// <summary>
/// 获取枚举成员的值(this是扩展方法的标志)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static int GetIndexInt(this Enum obj)
{
return Convert.ToInt32(obj);
}
/// <summary>
/// 获取枚举成员的值(this是扩展方法的标志)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetIndexString(this Enum obj)
{
return Convert.ToInt32(obj).ToString();
}
public static T ToEnum<T>(this string obj) where T : struct
{
if (string.IsNullOrEmpty(obj))
{
return default(T);
}
try
{
return (T)Enum.Parse(typeof(T), obj, true);
}
catch (Exception)
{
return default(T);
}
}
/// <summary>
/// 获取指定枚举成员的描述
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToDescriptionString(this Enum obj)
{
var attribs = (DescriptionAttribute[])obj.GetType().GetField(obj.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attribs.Length > 0 ? attribs[0].Description : obj.ToString();
}
/// <summary>
/// 根据枚举值,获取指定枚举类的成员描述
/// </summary>
/// <param name="type"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string GetDescriptionString(this Type type, int? id)
{
var values = from Enum e in Enum.GetValues(type)
select new { id = e.GetIndexInt(), name = e.ToDescriptionString() };
if (!id.HasValue) id = 0;
try
{
return values.ToList().Find(c => c.id == id).name;
}
catch
{
return "";
}
}
#endregion
}
}