更新:有一篇很好的文章解释了如何使用重构安全代码访问方法或属性并提供代码。 http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/
所有给出的答案都将起作用。但是,没有一个是重构安全的。我想我会提供一个更安全的重构解决方案。
//Create a dictionary of columnName => property info using the GetPropertyInfo method.
public static IDictionary<string, PropertyInfo> propertyInfos = new Dictionary<string, PropertyInfo>
{
{"Name", GetPropertyInfo((Customer c) => c.Name) }
};
List<Customer> Customers= new List<Customer> { new Customer { Name = "Peter Pan" } };
Customer customer = Customers[0];
string column = "Name";
PropertyInfo propertyInfo = propertyInfos[column];
//Set property
propertyInfo.SetValue(customer, "Captain Hook", null);
//Get property -- Returns Captain Hook
object propertyValue = propertyInfo.GetValue(customer, null);
我取自GetPropertyInfo
这个答案。我通过删除source
参数对其进行了轻微修改,因为您可以从HappyNomad 的评论中看到,最新版本的 C# 不需要它。
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo;
}
我的建议是更安全的重构,因为每次更改Name
属性时都会遇到编译时错误Customer
。
旁注:我同意Tim S.。您可能会找到比反射更安全、更高效的方法:)。