C# class []方法的重写自定义获取class中各变量

    技术2022-07-10  91

    public class A { public List<B> no1 = new List<B>(); public List<B> no2 = new List<B>(); public List<B> no3 = new List<B>(); public List<B> this[int key] { get { FieldInfo f = this.GetType().GetField("no" + key.ToString()); if(f==null) { return null; } return (List<B>)f.GetValue(this); } set { FieldInfo f = this.GetType().GetField("no" + key.ToString()); f.SetValue(this, value); } } }

    这样重写之后,A[1] 相当于是 A.no1

    Processed: 0.015, SQL: 9