关于PropertyInfo.GetValue()获取数组

syqslhc 2017-11-05 12:17:34

public virtual object GetValue(
object obj,
object[] index
)


使用PropertyInfo.GetValue()如何获取整个数组,并获取数组信息,比如数组长度,数组内各个值
现在知道的方式是

Object objs = propertyInfo.GetValue(obj, null);
foreach(var itor in (Array)objs)
{
//itor
}

请问除了这种方式还能怎样通过反射获取数组的值?
...全文
919 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
第02个小程序:遍历画笔(FlipThroughTheBrushes.cs) using System; using System.Reflection; using System.Windows; using System.Windows.Input; using System.Windows.Media; namespace Chapter02 { public class FlipThroughTheBrushes : Window { int index = 0; //索引值 PropertyInfo[] props; //属性数组 [STAThread] public static void Main() { Application app = new Application(); app.Run(new FlipThroughTheBrushes()); } public FlipThroughTheBrushes() { //取得Brushes类的成员,放在props中 props = typeof(Brushes).GetProperties(BindingFlags.Public | BindingFlags.Static); SetTitleAndBackground(); } //鼠标按下时 protected override void OnKeyDown(KeyEventArgs args) { if (args.Key == Key.Down || args.Key == Key.Up) { //Key.Down时index-1,Key.UP时index+1 index += args.Key == Key.Up ? 1 : props.Length - 1; //index对属性数组长度取余,防止索引越界 index %= props.Length; SetTitleAndBackground(); } base.OnKeyDown(args); } //设置背景 void SetTitleAndBackground() { Title = "Flip Through the Brushes - " + props[index].Name; Background = (Brush)props[index].GetValue(null, null); //设置背景画笔 } } } GetProperties()函数用于返回对象数组,参数是限制Brushes公开和静态的属性。其实这里可以不需要这样的限制,因为Brushes的属性本来全部都是public和static。 props[index].Name返回第index个属性的名称;props[index].GetValue(null, null)返回实际的SolidColorBrush对象,第一个参数是属性所在的对象,因为Brushes是一个静态属性,没有对应的对象,传入null;第二个参数只有在属性是索引器是才有必要。

110,533

社区成员

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

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

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