使用反射,获取含有属性"Text"的控件的ID属性的值ArrayList list1 = new ArrayList();
for(int i=0;i<context.Container.Components.Count;i++)
{
if(context.Container.Components[i].GetType().GetProperty("Text") != null)
{
Type typ  = context.Container.Components[i].GetType();
PropertyInfo objProperty = typ.GetProperty("Text");
Object objValue = new object();
objProperty.GetValue(objValue,null);
list1.Add(objValue);
}
return list1;出错信息是TargetException:对象与目标类型不匹配。
TargetException:
试图在空对象上调用非静态方法时引发 TargetException。发生这种情况的原因包括调用方无权访问成员、目标没有定义成员,等等。求教如何获取该属性的值?

解决方案 »

  1.   

    ArrayList list = new ArrayList();
    TextBox[] textboxes = new TextBox[5];
    for(int i = 0; i < textboxes.Length; i++)
    {
    textboxes[i] = new TextBox();
    textboxes[i].Name = "textbox"+i.ToString();
    list.Add(textboxes[i]); Type t = list[i].GetType();

    PropertyInfo info = t.GetProperty("Text");
    if(info != null)
    {
    MessageBox.Show(t.GetProperty("Name").GetValue(list[i],null).ToString());
    }
    }
      

  2.   

    问题是我这里的对象实例是未知类型……不一定是TextBox啊 !!用反射的话获取属性值是需要一个实例的吧(对非静态而言),我要搜索页面下所有含有Text属性的控件(不一定只是TextBox类型噢),并将这些控件的ID属性值放入一个string[] 里……
    关键就是使用反射无法确定调用返回的实例类型……
    也就是这里:
    objProperty.GetValue(objValue,null);的objObject
      

  3.   

    /// <summary>
    /// 根据属性名获取属性的值并返回值
    /// </summary>
    /// <param name="ClassInstance">类实例</param>
    /// <param name="PropertyName">属性名</param>
    /// <returns></returns>
    public object GetPropertyValue(object ClassInstance,string PropertyName)
    {
    Type myType = ClassInstance.GetType();
    PropertyInfo myPropertyInfo = myType.GetProperty(PropertyName,BindingFlags.Instance|BindingFlags.NonPublic|BindingFlags.Public);
    return myPropertyInfo.GetValue(ClassInstance,null);
    }