C#-使用反射从列表中提取值列表<;类别>;
我有一个包含类的列表,希望能够使用反射来迭代该类中的每个属性,并生成包含每个属性值的列表。使用反射获取所有属性没有问题,但我失败的地方在于语法中迭代提取每个属性值的列表 示例代码:C#-使用反射从列表中提取值列表<;类别>;,c#,generics,reflection,collections,C#,Generics,Reflection,Collections,我有一个包含类的列表,希望能够使用反射来迭代该类中的每个属性,并生成包含每个属性值的列表。使用反射获取所有属性没有问题,但我失败的地方在于语法中迭代提取每个属性值的列表 示例代码: public class ExampleClass { public double Val1 {get; set;} public double Val2 { get; set; } public double Val3 { get; set; } public ExampleCla
public class ExampleClass
{
public double Val1 {get; set;}
public double Val2 { get; set; }
public double Val3 { get; set; }
public ExampleClass(double val1, double val2, double val3)
{
this.Val1 = val1;
this.Val2 = val2;
this.Val3 = val3 ;
}
}
public class Main
{
public Main()
{
List<ExampleClass> exampleList = new List<ExampleClass>();
exampleList.Add(new ExampleClass(1.1, 1.2, 1.3));
exampleList.Add(new ExampleClass(2.1, 2.2, 2.3));
exampleList.Add(new ExampleClass(3.1, 3.2, 3.3));
List<PropertyInfo> properties = exampleList[0]
.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.ToList();
foreach (PropertyInfo prop in properties)
{
// Extract each property into a list, e.g.
// 1st pass: list containing 1.1, 2.1, and 3.1
// 2nd pass: list containing 1.2, 2.2 and 3.2
// 3rd pass: list containing 1.3, 2.3 and 3.3
}
}
}
不幸的是,我的最佳猜测如下所示,并生成“对象引用未设置为对象实例”错误
var test1 = collectionCompletionList.GetType().GetProperty(prop.Name).GetValue(collectionCompletionList, null);
我在这里遗漏了什么(大概)简单的东西?你几乎明白了。
PropertyInfo
类的GetValue
方法将其属性值作为参数返回的对象。因此,您需要将列表中的项目传递给它,而不是列表本身
foreach (PropertyInfo prop in properties) {
var propertiesValues = exampleList.Select(o => prop.GetValue(o)).ToList();
}
您应该迭代集合和属性
Dictionary<string, ArrayList> allIterationValues = new Dictionary<string, ArrayList>();
foreach (PropertyInfo prop in properties)
{
ArrayList iterationList = new ArrayList();
allIterationValues.Add(prop.Name, iterationList);
foreach (var element in exampleList)
{
iterationList.Add(prop.GetValue(element, null));
}
}
// Check the value of allIterationValues here
字典头韵值=新字典();
foreach(PropertyInfo属性中的属性)
{
ArrayList iterationList=新建ArrayList();
添加(prop.Name,iterationList);
foreach(示例列表中的var元素)
{
Add(prop.GetValue(element,null));
}
}
//在此处检查头韵值
Dictionary<string, ArrayList> allIterationValues = new Dictionary<string, ArrayList>();
foreach (PropertyInfo prop in properties)
{
ArrayList iterationList = new ArrayList();
allIterationValues.Add(prop.Name, iterationList);
foreach (var element in exampleList)
{
iterationList.Add(prop.GetValue(element, null));
}
}
// Check the value of allIterationValues here