您可以为此使用表达式。用法如下所示:
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 方式实际上是一个编译时功能,因此不会对运行时产生影响。但是,正如我在评论中已经说过的,它不适用于给定的场景。