我的一个类中有100个属性,命名规律为Chk1,Chk2......Chk100现在我要用一个for循环为所有属性赋值相同的值"abc",如:
for (int i=1;i<=100;i++)
{
   obj.Chk(i) = "abc"; //我不想写100行代码,用i变量一句怎么搞定?
}

解决方案 »

  1.   

    用索引器
    索引器是一种成员,它使对象能够用与数组相同的方式进行索引。属性启用类似字段的访问,而索引器启用类似数组的访问。例如,请看一下前面研究过的 Stack 类。该类的设计者可能想提供类似数组的访问,以便不必执行 Push 和 Pop 操作,就可以检查或改变堆栈上的各个项。也就是说,使 Stack 类既是链接表,又可像数组一样方便地对它进行访问。索引器声明类似于属性声明,主要区别是索引器是无名称的(由于 this 被索引,因此在声明中使用的“名称”为 this),而且索引器包含索引参数。索引参数在方括号中提供。示例using System;
    public class Stack
    {
       private Node GetNode(int index) {
          Node temp = first; 
          while (index > 0 && temp != null) {
             temp = temp.Next;
             index--;
          }
          if (index < 0 || temp == null)
             throw new Exception("Index out of range.");      return temp;
       }
       public object this[int index] {
          get {
             return GetNode(index).Value;
          }
          set {
             GetNode(index).Value = value;
          }
       }
       ...
    }
    class Test
    {
       static void Main() {
          Stack s = new Stack();
          s.Push(1);
          s.Push(2);
          s.Push(3);
          s[0] = 33;   // Changes the top item from 3 to 33
          s[1] = 22;   // Changes the middle item from 2 to 22
          s[2] = 11;   // Changes the bottom item from 1 to 11
       }
    }