コードのページは 1,000 語なので、Microsoft がPrismでそれを行う方法は次のとおりです。
///<summary>
/// Provides support for extracting property information based on a property expression.
///</summary>
public static class PropertySupport
{
/// <summary>
/// Extracts the property name from a property expression.
/// </summary>
/// <typeparam name="T">The object type containing the property specified in the expression.</typeparam>
/// <param name="propertyExpression">The property expression (e.g. p => p.PropertyName)</param>
/// <returns>The name of the property.</returns>
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="propertyExpression"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when the expression is:<br/>
/// Not a <see cref="MemberExpression"/><br/>
/// The <see cref="MemberExpression"/> does not represent a property.<br/>
/// Or, the property is static.
/// </exception>
public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException("propertyExpression");
}
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException(Resources.PropertySupport_NotMemberAccessExpression_Exception, "propertyExpression");
}
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException(Resources.PropertySupport_ExpressionNotProperty_Exception, "propertyExpression");
}
var getMethod = property.GetGetMethod(true);
if (getMethod.IsStatic)
{
throw new ArgumentException(Resources.PropertySupport_StaticExpression_Exception, "propertyExpression");
}
return memberExpression.Member.Name;
}
}
属性を考慮に入れたい場合は、もう少し複雑になりますが、 を受け入れExpression<Func<T>>
て対象となるプロパティの名前を釣り上げるという一般的な考え方は同じです。
更新:そのままでは、メソッドは 1 つのパラメーターのみを受け入れます。私はそれをガイドラインとして提供しただけです。もちろん、アイデアは一般化できます。
public static string[] ExtractPropertyNames<T>(
Expression<Func<T, object>> propertyExpression)
このメソッドは、T を受け取る式を受け入れ、後で反映できる匿名型を返します。2 番目の型パラメーターを置き換えることもできますがobject
、ここでは何もしません。なぜなら、やりたいことは型を反映することだけだからです。