-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathStringEnumeration.cs
More file actions
106 lines (89 loc) · 3.08 KB
/
Copy pathStringEnumeration.cs
File metadata and controls
106 lines (89 loc) · 3.08 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
namespace OpenStack.Serialization
{
/// <summary>
/// Using classes for enumerations allows us to use inheritance and enable API versions or other providers to share and extend "enums"
/// <seealso href="https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/"/>
/// </summary>
/// <exclude />
[JsonConverter(typeof(StringEnumerationConverter))]
public abstract class StringEnumeration : IComparable
{
/// <summary />
protected StringEnumeration()
{ }
/// <summary />
protected StringEnumeration(string displayName)
{
DisplayName = displayName;
}
/// <summary />
public string DisplayName { get; protected set; }
/// <summary />
public override string ToString()
{
return DisplayName;
}
/// <summary />
public static IEnumerable<T> GetAll<T>()
where T : StringEnumeration
{
return GetAll(typeof(T)).Cast<T>();
}
/// <summary />
public static IEnumerable<StringEnumeration> GetAll(Type type)
{
IEnumerable<FieldInfo> fields = type
.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static)
.Where(field => field.FieldType == type);
return fields.Select(info => info.GetValue(null)).Cast<StringEnumeration>();
}
/// <summary />
public override bool Equals(object obj)
{
var otherValue = obj as StringEnumeration;
if (otherValue == null)
{
return false;
}
var typeMatches = GetType().Equals(obj.GetType());
var valueMatches = DisplayName.Equals(otherValue.DisplayName);
return typeMatches && valueMatches;
}
/// <summary />
public static bool operator ==(StringEnumeration left, StringEnumeration right)
{
return Equals(left, right);
}
/// <summary />
public static bool operator !=(StringEnumeration left, StringEnumeration right)
{
return !Equals(left, right);
}
/// <summary />
public override int GetHashCode()
{
return DisplayName.GetHashCode();
}
/// <summary />
public static T FromDisplayName<T>(string displayName)
where T : StringEnumeration
{
return (T)FromDisplayName(typeof(T), displayName);
}
/// <summary />
public static StringEnumeration FromDisplayName(Type objectType, string displayName)
{
return GetAll(objectType).FirstOrDefault(item => item.DisplayName == displayName);
}
/// <summary />
public int CompareTo(object other)
{
return string.Compare(DisplayName, ((StringEnumeration)other).DisplayName, StringComparison.Ordinal);
}
}
}