2 回答
TA贡献1827条经验 获得超8个赞
你可以用表达式解析它:
public string NameOf<TTarget, TProperty>(TTarget dontcare, Expression<Func<TTarget, TProperty>> propertySelector)
{
var name = propertySelector.Parameters.Single().Name;
var expression = propertySelector.ToString();
// remove 'x => '
expression = Regex.Replace(expression, Regex.Escape(name) + " => ", "");
// replace 'x.' with '@'
expression = Regex.Replace(expression, Regex.Escape(name) + @"\.", "");
return expression;
}
public string NameOf<TProperty>(Expression<Func<TProperty>> propertySelector)
{
var expression = propertySelector.ToString();
// remove '() => '
expression = Regex.Replace(expression, @"\(\) => ", "");
// replace 'value(...)' with '@'
expression = Regex.Replace(expression, @"value\([^\)]+\).", "");
return expression;
}
用法:
var context = new Context();
NameOf(context, x => x.Inner.Inner.Value).Dump(); // Inner.Inner.Value
NameOf(() => context.Inner.Inner.Value).Dump(); // context.Inner.Inner.Value
public class Context
{
public Context Inner => this;
public int Value => 1;
}
- 2 回答
- 0 关注
- 173 浏览
添加回答
举报