public void EnumConvertTest() { Enum <Color> .TryConvert(Color.Red).ShouldBe(Color.Red); Enum <Color> .TryConvert(2).ShouldBe(Color.Green); Enum <Color> .TryConvert(2ul).ShouldBe(Color.Green); Enum <Color> .TryConvert(2f).ShouldBe(Color.Green); Enum <Color> .TryConvert("Red").ShouldBe(Color.Red); Enum <Color> .TryConvert("GREEN").ShouldBe(Enum <Color> .DefaultValue); Enum <Color> .TryConvert(100).ShouldBe(Enum <Color> .DefaultValue); Enum <Color> .TryConvert(new object()).ShouldBe(Enum <Color> .DefaultValue); Color.Green.ToValue <int>().ShouldBe(2); Color.Green.ToValue <float>().ShouldBe(2f); Color.Green.ToValue <string>().ShouldBe("Green"); Should.Throw <InvalidOperationException>(() => Enum <Color> .Convert(new object(), out var color, enableDefaultValue: false)); // System.InvalidOperationException: Unknown enum type Should.Throw <ConvertObjectToEnumException>(() => Enum <Color> .Convert(CarClass.Van, out var color, enableDefaultValue: false)); Enum <Color> .Convert(CarClass.Van, out var color, enableDefaultValue : true).ShouldBe(false); color.ShouldBe(Enum <Color> .DefaultValue); }
static T Create <T, P>(P value) { if (typeof(T).Equals(typeof(FamilyMember)) && typeof(P).Equals(typeof(FamilyRelation))) { FamilyRelation relation = Enum <FamilyRelation, P> .Convert(value); //FamilyRelation relation = (FamilyRelation)(object)value; //FamilyRelation relation = (FamilyRelation)value; return((T)(object)new FamilyMember(relation)); } throw new NotImplementedException(); }
public static TEnum Convert <TEnum>(this Enum enumValue) where TEnum : struct, Enum { return(enumValue.Convert <TEnum>(ignoreCase: false)); }