C# non-boxing conversion of generic enum to int?

前端 未结 9 1958
庸人自扰
庸人自扰 2020-12-04 07:31

Given a generic parameter TEnum which always will be an enum type, is there any way to cast from TEnum to int without boxing/unboxing?

See this example code. This w

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 07:53

    ...I'm even 'later' : )

    but just to extend on the previous post (Michael B), which did all the interesting work

    and got me interested into making a wrapper for a generic case (if you want to cast generic to enum actually)

    ...and optimized a bit... (note: the main point is to use 'as' on Func<>/delegates instead - as Enum, value types do not allow it)

    public static class Identity
    {
        public static readonly Func Cast = (Func)((x) => x) as Func;
    }
    

    ...and you can use it like this...

    enum FamilyRelation { None, Father, Mother, Brother, Sister, };
    class FamilyMember
    {
        public FamilyRelation Relation { get; set; }
        public FamilyMember(FamilyRelation relation)
        {
            this.Relation = relation;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            FamilyMember member = Create(FamilyRelation.Sister);
        }
        static T Create(P value)
        {
            if (typeof(T).Equals(typeof(FamilyMember)) && typeof(P).Equals(typeof(FamilyRelation)))
            {
                FamilyRelation rel = Identity.Cast(value);
                return (T)(object)new FamilyMember(rel);
            }
            throw new NotImplementedException();
        }
    }
    

    ...for (int) - just (int)rel

提交回复
热议问题