public static class Enum
{
private static int Random(int start, int end) =>
new Random().Next(start, end);
private static System.Array GetArray<T>() where T : struct, IConvertible =>
System.Enum.GetValues(typeof(T));
public static int GetSize<T>() where T : struct, IConvertible =>
GetArray<T>().Length;
public static int GetValue<T>(this T @enum) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{typeof(T)} is not enum");
return (int)(object)@enum;
}
public static int GetIndex<T>(this T @enum) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{typeof(T)} is not enum");
return System.Array.IndexOf(GetArray<T>(), @enum);
}
/// index to enum
public static T GetEnum<T>(this int index) where T : struct, IConvertible
{
var array = System.Enum.GetValues(typeof(T));
return (T)array.GetValue(index);
}
/// [0,Length)
public static T Random<T>() where T : struct, IConvertible =>
Random(0, GetSize<T>()).GetEnum<T>();
/// [start,end]
public static T Random<T>(T start, T end) where T : struct, IConvertible =>
Random<T>(start.GetIndex(), end.GetIndex() + 1);
/// [start,end)
public static T Random<T>(int start, int end) where T : struct, IConvertible
{
var size = GetSize<T>();
if (start < 0) start = 0;
if (end > size) end = size;
return Random(start, end).GetEnum<T>();
}
}
枚举
// value
public enum EnumShape // length = 8
{
None, // 0
Direct, // 1
Square, // 2
Cross, // 3
Circle, // 4
BigSquare,// 5
BigCross, // 6
BigCircle,// 7
}
public enum EnumInNeedShape // length = 5
{
None, // 0
Square = EnumShape.Square, // 2
Cross = EnumShape.Cross, // 3
Circle = EnumShape.Circle, // 4
Triangle = 10, // 10
}
测试GetEnum
class Test{
pubilc void Test(){
0.GetEnum<EnumShape>();// None
1.GetEnum<EnumShape>();// Square
2.GetEnum<EnumShape>();// Cross
3.GetEnum<EnumShape>();// Circle
4.GetEnum<EnumShape>();// Triangle
10.GetEnum<EnumShape>();// throw IndexOutOfRangeException
}
}
测试GetValue,GetRandom
public class Test
{
pubilc void Test()
{
$"Square {(int)EnumInNeedShape.Square}".LogLine(); // 2
$"Square {(int)EnumInNeedShape.Circle}".LogLine(); // 4
EnumInNeedShape.Triangle.GetValue().LogLine(); // 10
EnumInNeedShape.Triangle.GetIndex().LogLine(); // 4
Enum.Random(EnumInNeedShape.None, EnumInNeedShape.Triangle).LogLine(); // [None, Triangle]
Enum.Random(EnumShape.None, EnumShape.AltCircle).LogLine(); // [None, AltCircle]
Enum.Random<EnumShape>(0, 9).LogLine(); // [None, AltCircle]
Enum.Random(EnumInNeedShape.Square, EnumInNeedShape.Circle).LogLine(); // [Square, Circle]
Enum.Random(EnumInNeedShape.Cross, EnumInNeedShape.Triangle).LogLine(); // [Cross, Triangle]
}
}