Descriptor Pattern
// C#, OOP
public class SearchType : Descriptor
{
public static readonly SearchType Search = new SearchType(1, "search");
public static readonly SearchType Category = new SearchType(-1, "category");
public static readonly SearchType GlobalFilter = new SearchType(-1, "globalfilter");
public static readonly SearchType Merchant = new SearchType(-1, "merchant");
public static readonly SearchType Brand = new SearchType(-1, "brand");
public static IEnumerable<SearchType> All = new List<SearchType> { Search, Category, GlobalFilter, Merchant, Brand };
private SearchType(int value, string state)
: base(value, state)
{
}
public static SearchType From(string state)
{
var searchType = All.FirstOrDefault(s => s.ToString() == state);
if (searchType == null)
{
throw new ArgumentException(string.Format("Invalid state value: {0}", state), nameof(state));
}
return searchType;
}
}
// Base Class:
public abstract class Descriptor
{
public int Value { get; }
public string State { get; }
protected Descriptor(int value, string state)
{
Value = value;
State = state;
}
public override string ToString()
{
return State;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as Descriptor;
if (ReferenceEquals(other, null)) return false;
return Value == other.Value;
}
public static implicit operator int(Descriptor descriptor)
{
return descriptor.Value;
}
}