关于System.Reflection.PropertyInfo 的setvalue,如果属性是集合类型,应如何赋值?

Scarroot 2007-06-13 08:35:02
object [] aryValue = new object[]{"x","y","z"};
System.Type tt = typeof(System.Windows.Forms.ComboBox);
System.Reflection.PropertyInfo pi = tt.GetProperty("Items");
//pi.SetValue()
...全文
1079 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackeyabc 2008-07-12
  • 打赏
  • 举报
回复
收藏先
wazdo 2007-08-09
  • 打赏
  • 举报
回复
小吴同志啊.
danjiewu 2007-06-13
  • 打赏
  • 举报
回复
GetProperty("this");写错了
奇怪明明写的时候用this取的时候却要用Item,真不习惯。
Scarroot 2007-06-13
  • 打赏
  • 举报
回复
谢谢,hbxtlhx(平民百姓-自已动手,丰衣足食),danjiewu(阿丹)

要的就是这效果.非常感谢.
北京的雾霾天 2007-06-13
  • 打赏
  • 举报
回复
为了好理解,我下面的代码加了注释:

object[] aryValue = new object[] { "x", "y", "z" };

System.Type tt = typeof(ComboBox);
//得到的是ComboBox.Items属性
System.Reflection.PropertyInfo pi = tt.GetProperty("Items");
//得到的是ComboBox.Items属性的实例
object obj = pi.GetValue(this.comboBox1, new object[] {});
//因为Items是一个类(集合),所以要先得到集合的索引,从而通过索引设置Items的值
System.Reflection.PropertyInfo pi1 = obj.GetType().GetProperty("Item");
for (int i = 0; i < aryValue.Length; i++)
{
//为每一个集合中的值设置新的值,当然要注意Items的元素个数
//这里要通过Object数组来指定值要传到Items哪一个索引的元素下
pi1.SetValue(obj, aryValue[i], new object[] { i });
}

//为了测试这里输出了设置了新的值以后的Items中的值
for (int i = 0; i < this.comboBox1.Items.Count; i++)
{
Console.WriteLine(this.comboBox1.Items[i]);
}
北京的雾霾天 2007-06-13
  • 打赏
  • 举报
回复
你用如下的代码试试吧:

object[] aryValue = new object[] { "x", "y", "z" };
System.Type tt = typeof(ComboBox);
System.Reflection.PropertyInfo pi = tt.GetProperty("Items");
object obj = pi.GetValue(this.comboBox1, new object[] {});

System.Reflection.PropertyInfo pi1 = obj.GetType().GetProperty("Item");
for (int i = 0; i < aryValue.Length; i++)
{
pi1.SetValue(obj, aryValue[i], new object[] { i });
}

for (int i = 0; i < this.comboBox1.Items.Count; i++)
{
Console.WriteLine(this.comboBox1.Items[i]);
}
Scarroot 2007-06-13
  • 打赏
  • 举报
回复
PropertyInfo indexProperty = propertyType.GetProperty("this");

这句得到null
Scarroot 2007-06-13
  • 打赏
  • 举报
回复
谢谢
danjiewu(阿丹)
but
indexProperty.SetValue(itemCollection,aryValue[i],i); 这句过不了.


danjiewu 2007-06-13
  • 打赏
  • 举报
回复
lz说的Items[x]并非是索引属性,它的索引不是Items这个属性的,而是Items的类型xxxItemCollection的。

object [] aryValue = new object[]{"x","y","z"};
System.Type tt = typeof(System.Windows.Forms.ComboBox);
System.Reflection.PropertyInfo pi = tt.GetProperty("Items");
Type propertyType = pi.PropertyType;
PropertyInfo indexProperty = propertyType.GetProperty("this");
object itemCollection = pi.GetValue(yourComboBox,null);
for(int i = 0; i < aryValue.Length;i++)
indexProperty.SetValue(itemCollection,aryValue[i],i);
Scarroot 2007-06-13
  • 打赏
  • 举报
回复
pi.SetValue(this.comboBox1,null,aryValue);

出错显示:未找到属性设置方法.
就说对于System.Windows.Forms.ComboBox 的Items 属性
如何赋值.

或如何调用AddRange方法.
北京的雾霾天 2007-06-13
  • 打赏
  • 举报
回复
如果是索引属性可以通过最后一个参数index来指定,如果是非索引的是null就可以了.

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧