我有一个包含类的List,并希望能够使用反射来遍历该类中的每个属性,并生成包含每个属性值的List.我使用反射来获取所有属性没有问题,但是我失败的地方在于语法迭代地提取每个属性值的列表.
示例代码:
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() { ListexampleList = new List (); 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 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 test = exampleList.Select(X => X.Val1).ToList();
不幸的是,我最好的猜测看起来如下,并生成"对象引用未设置为对象的实例"错误
var test1 = collectionCompletionList.GetType().GetProperty(prop.Name).GetValue(collectionCompletionList, null);
我想念的是什么(大概)简单的事情?
你几乎得到了它.该类的GetValue
方法PropertyInfo
将对象的属性值作为参数返回.所以你需要传递列表中的项目,而不是列表本身.
foreach (PropertyInfo prop in properties) { var propertiesValues = exampleList.Select(o => prop.GetValue(o)).ToList(); }