- 爱易网页
 
                        - 
                            C#教程
 
                        - 非常深奥的有关问题!涉及索引器、装箱、泛型等!综合技术 
 
                         
                    
                    
                    日期:2014-05-19  浏览次数:21063 次 
                    
                        
                         非常深奥的问题!涉及索引器、装箱、泛型等!综合技术!
应用场景: 
 在一个类中包含多种值类型的属性,现在希望通过构建多个索引器或是可以遍历访问的数组对象,来访问此类的实例中的多种类型属性。 
 比如string类型的索引器中索引0为“Name”属性,索引1为“Info”属性;而int类型的索引器中索引0为“ID”属性,索引1为“Age”属性。所有属性不单应可以读取,还应当能赋值,并且在类的实例中的属性发生改变时也能读取到改变后的值。 
  
 实现构想: 
  
 1.泛型索引器: 
 public    <T>    this <T> [int   index] 
 { 
       get 
       { 
       //遍历比较属性并返回相应序列索引的指定类型的值 
       int   x   =   0; 
       if   (ID.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   return   ID;   } 
       if   (Age.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   return   Age;   } 
       if   (Name.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   return   Name;   } 
       if   (Info.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   return   Info;   } 
 ... 
       return   null; 
       } 
       set 
       { 
       int   x   =   0; 
       if   (ID.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   ID   =   value;   } 
       if   (Age.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   Age   =   value;   } 
       if   (Name.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   Name   =   value;   } 
       if   (Info.GetType()   ==   typeof(T)   &&   x++   ==   index)   {   Info   =   value;   } 
 ... 
       } 
 } 
 失败——索引器不支持泛型! 
  
 2.依靠索引器参数传递类型值: 
 public   object   this[int   index,Type   type] 
 { 
       ...与上文类似,不再累述 
 } 
 失败——无法给强类型属性赋予object值! 
  
 3.装箱并放入泛型列表List <> 中 
 public   List <object>    获取属性索引 <T> () 
 { 
       List <object>    list=new   List <object> (); 
       object   o   =   new   object(); 
       if   (ID.GetType()   ==   typeof(T))   {   o=ID;list.Add(o);   } 
       if   (Age.GetType()   ==   typeof(T))   {   o=Age;list.Add(o);   } 
 ... 
       return   list; 
 } 
 失败——装箱后无法和原属性挂接,双方各不相干,修改属性后在对方处无效。 
  
 4.用一个无意义的参数标识索引器,进行重载: 
 public   int   this[int   index,int   type] 
 { 
          get 
       { 
                switch(index) 
                { 
                      case   0:return   ID; 
                      case   1:return   Age; 
                      ... 
                      default   retun   null; 
                } 
       } 
       set 
       { 
                   .... 
       } 
 } 
  
 public   string   this[int   index,string   type] 
 { 
          get