斯蒂芬大帝
你可以用表达式解析它: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.ValueNameOf(() => context.Inner.Inner.Value).Dump(); // context.Inner.Inner.Valuepublic class Context{ public Context Inner => this; public int Value => 1;}