一个简单的解决方案是使用 LINQ 的Select
方法:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class PersonCollection : List<Person>
{
public object[] GetValues(string propertyName)
{
if (propertyName == "Name")
{
return this.Select(p => p.Name).ToArray();
}
else if (propertyName == "Property1")
{
return this.Select(p => p.Property1).ToArray();
}
else if (propertyName == "Property2")
{
return this.Select(p => p.Property1).ToArray();
}
// best way to implement this method?
return null;
}
}
您还可以使用表达式树来允许将类型安全的访问器 lambda 用作参数:
public object[] GetValues(Expression<Func<Person, object>> propertyNameExpression)
{
var compiledPropertyNameExpression = propertyNameExpression.Compile();
if (propertyNameExpression.Body.NodeType == ExpressionType.MemberAccess)
{
return this.Select(compiledPropertyNameExpression).ToArray();
}
throw new InvalidOperationException("Invalid lambda specified. The lambda should select a property.");
}
然后,您可以按如下方式使用它:
var personNames = personCollection.GetValues(p => p.Name)