使用反射,获取含有属性"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。发生这种情况的原因包括调用方无权访问成员、目标没有定义成员,等等。求教如何获取该属性的值?
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。发生这种情况的原因包括调用方无权访问成员、目标没有定义成员,等等。求教如何获取该属性的值?
解决方案 »
- 注册activeX控件问题,.net开发的控件
- vs2010无法切换设计视图
- 一个函数,传入的是arraylist动态数组,返回动态数组的个数count。那么能得到arraylist吗?
- 这样的情况下,数据存到数据库里,怎么样比较快?
- float数据添入数据库问题
- 大家好~小弟新来的~想问个关于BUTTON事件的问题
- 如何让TreeView的父节点纵向排列,子节点横向排列
- Word文档合并问题?
- c#里如可表示IS1,IS2,IS3
- 什么时候用泛型?泛型有什么好处?
- 如何判断进程是否关闭 如果进程关闭的话 再次调用他
- XML文件一个节点中有1000个字节点,我如何分段读取1-500个节点第二次从500-1000来段读取
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());
}
}
关键就是使用反射无法确定调用返回的实例类型……
也就是这里:
objProperty.GetValue(objValue,null);的objObject
/// 根据属性名获取属性的值并返回值
/// </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);
}