这样的代码
Info ci = new Info();string name = crop(cb_croplist.Text);for (int i = 0; i < ci.name.Length; i++) {
    listBox1.Items.Add(ci.name[i]);
}我的目的:用crop方法根据combox.text(cb_croplist.Text)选中的内容计算,假设返回值是字符串 list,把它赋值给name然后用list代替这句ci.name.Length里的 name,
就是变成ci.list.length;怎么能做到这样呢??
现在这样写,会出错,说Info里不包含name的定义。

解决方案 »

  1.   

    说明Info中没有name的属性 get return 方法设置属性 试试 
      

  2.   

     public class info
        {
            private string[] _aa = new string[] { "ss", "bb", "cc" };        public string[] AA
            {
                get { return _aa; }
                set { _aa = value; }
            }

        }
    //另一个类的方法
            private void button1_Click(object sender, EventArgs e)
            {
               
                info ci = new info();
                string name = "AA";// crop(cb_croplist.Text); 
                Type t = ci.GetType();
                PropertyInfo pi = t.GetProperty(name);
               object objTemp =  pi.GetValue(ci, new object[] { });
               string[] strTemp = objTemp as string[];
               for (int i = 0; i < strTemp.Length; i++)
               {
                   MessageBox.Show(strTemp[i]);
               }        }
      

  3.   

    object objTemp =  pi.GetValue(ci, new object[] { });  
    错在这行:
    未将对象引用设置到对象的实例。它上面一行的pi是null。
      

  4.   

    搞个 property bag 模拟一下撒// IDictionary 来维护
    public object this[string propertyName]
    {
      get {;}
      set {;}
    }
      

  5.   


    谢谢,,我调试好了。。你在info类里定义了这个
    public string[] AA
            {
                get { return _aa; }
                set { _aa = value; }
            }而我工程里的这个类全是我定义的数组。没有,get和set.
    现在可以用。不过有点不明白。
    Type t = ci.GetType();
    PropertyInfo pi = t.GetProperty(name);
    object objTemp =  pi.GetValue(ci, new object[] { });
    尤其是pi.GetValue(ci, new object[] { });的参数。不明白。
    看了,msdn,可是就一句话。看不懂。能帮我解释一下这三句吗??
    谢谢
      

  6.   

    去找反射的资料看看就好了,这是反射的最简单应用
    我的email:[email protected],有问题再联系