关于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
}

请问除了这种方式还能怎样通过反射获取数组的值?
...全文
1063 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
【源码免费下载链接】:https://renmaiwang.cn/s/5p4v7 在C#编程中,反射是一种强大的机制,它允许运行时检查和操作程序集、类型、方法、属性等元数据。反射通常用于动态类型创建、执行未事先硬编码的方法,以及在运行时发现类的结构。在本文中,我们将探讨如何使用反射遍历一个对象的所有属性及其对应的值。我们需要获取对象的`Type`对象。`Type`对象代表了一个类的元数据,它包含了关于类的所有信息,包括其属性、方法、构造函数等。以下是如何获取对象的`Type`:```csharpType t = tc.GetType();```在这里,`tc`是类的实例,`GetType()`方法返回与`tc`关联的`Type`对象。接下来,我们可以调用`Type.GetProperties()`来获取类中定义的所有属性。`GetProperties()`返回一个`PropertyInfo[]`数组,其中包含类的所有公共属性。如果需要访问非公共属性,可以使用`GetProperties(BindingFlags)`并提供适当的绑定标志,如`BindingFlags.NonPublic`。```csharpforeach (PropertyInfo pi in t.GetProperties()){ // 在这里,pi是PropertyInfo对象,表示类的一个属性}```一旦我们有了`PropertyInfo`对象,我们可以通过调用`GetValue()`方法来获取属性的当前值。`GetValue()`接受两个参数:一个是对象实例,另一个是可选的索引参数(对于索引属性)。```csharpobject value1 = pi.GetValue(tc, null);```在这里,`null`参数表示我们没有索引器,因为我们遍历的是非索引属性。此外,我们可以获取属性的名字,以便
第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;第二个参数只有在属性是索引器是才有必要。

111,120

社区成员

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

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

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