E_T

导航

知识点

Posted on 2019-08-16 15:43  E_T  阅读(103)  评论(0编辑  收藏  举报

 

 

返回只读集合

        List<PaymentMethod> _paymentMethods;
        public IEnumerable<PaymentMethod> PaymentMethods => _paymentMethods.AsReadOnly();

 

自定枚举

    public class CardType : SeedWrok.Enumeration
    {
        public static CardType Amex = new CardType(1, "Amex");
        public static CardType Visa = new CardType(2, "Visa");
        public static CardType MasterCard = new CardType(3, "MasterCard");
        public CardType(int id,string name) : base(id, name) { }
    }

    public abstract class Enumeration : IComparable
    {
        public string Name { get; private set; }
        public int Id { get; private set; }
        protected Enumeration(int id, string name)
        {
            Id = id;
            Name = name;
        }
        public override int GetHashCode() => Id.GetHashCode();
        public override bool Equals(object obj)
        {
            var temp = obj as Enumeration;
            if (temp == null)
                return false;
            var typeMatch = GetType().Equals(temp.GetType());
            var valueMatch = temp.Id.Equals(Id);
            return typeMatch && valueMatch;
        }
        public int CompareTo(object obj) => Id.CompareTo(((Enumeration)obj).Id);
        public static IEnumerable<T> GetAll<T>() where T:Enumeration
        {
            var fields = typeof(T).GetFields();
            return fields.Select(s => s.GetValue(null)).Cast<T>();静态字段使用参数null,Cast转为相应强类型
        }
    }