これには式を使用できます。使用法は次のようになります。
Magic_GetName<Foo>(x => x.Bar)
の実装は次のMagic_GetName
ようになります。
public static string Magic_GetName<TClass>(
Expression<Func<TClass, object>> propertyExpression)
{
propertyExpression.Dump();
var body = propertyExpression.Body as UnaryExpression;
if (body == null)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The body of the 'propertyExpression' should be an " +
"unary expression, but it is a {0}",
propertyExpression.Body.GetType()));
}
var memberExpression = body.Operand as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The operand of the body of 'propertyExpression' should " +
"be a member expression, but it is a {0}",
propertyExpression.Body.GetType()));
}
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
"The member used in the expression should be a property, " +
"but it is a {0}",
memberExpression.Member.GetType()));
}
return propertyInfo.Name;
}
更新:
この質問のタイトルは、「コンパイル時にプロパティ名を取得する」です。
私の答えは実際にはそうではありません。メソッドMagic_GetName
は実行時に実行されるため、パフォーマンスに影響があります。
一方、CallerMemberName
属性を使用する .NET 4.5 の方法は、実際にはコンパイル時の機能であり、ランタイムへの影響はありません。ただし、コメントで既に述べたように、特定のシナリオには適用できません。