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 關注
- 202 瀏覽
添加回答
舉報