更新: リファクタリング セーフ コードを使用してメソッドまたはプロパティにアクセスする方法を説明し、コードを提供する素敵な投稿があります。 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
から取ってきました。HappyNomadさんのコメントで最新バージョンのC#では必要ないことがわかるので、パラメータを削除して少し修正しました。source
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
。
補足:ティム S.に同意します。リフレクションよりも安全でパフォーマンスの高い方法を見つけることができるでしょう:)。