猿问

有没有更好的方法将虚线路径作为字符串?

有没有更好的方法将虚线路径变成字符串?


//I can do something ugly like

$"{nameof(obj)}.{nameof(obj.RelatedObj)}.{nameof(obj.RelatedObj.Field)}";

我在为这个问题寻找更好的解决方案时遇到了问题。


慕盖茨4494581
浏览 174回答 2
2回答

斯蒂芬大帝

你可以用表达式解析它:public string NameOf<TTarget, TProperty>(TTarget dontcare, Expression<Func<TTarget, TProperty>> propertySelector){&nbsp; &nbsp; var name = propertySelector.Parameters.Single().Name;&nbsp; &nbsp; var expression = propertySelector.ToString();&nbsp; &nbsp; // remove 'x => '&nbsp; &nbsp; expression = Regex.Replace(expression, Regex.Escape(name) + " => ", "");&nbsp; &nbsp; // replace 'x.' with '@'&nbsp; &nbsp; expression = Regex.Replace(expression, Regex.Escape(name) + @"\.", "");&nbsp; &nbsp; return expression;}public string NameOf<TProperty>(Expression<Func<TProperty>> propertySelector){&nbsp; &nbsp; var expression = propertySelector.ToString();&nbsp; &nbsp; // remove '() => '&nbsp; &nbsp; expression = Regex.Replace(expression, @"\(\) => ", "");&nbsp; &nbsp; // replace 'value(...)' with '@'&nbsp; &nbsp; expression = Regex.Replace(expression, @"value\([^\)]+\).", "");&nbsp; &nbsp; 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{&nbsp; &nbsp; public Context Inner => this;&nbsp; &nbsp; public int Value => 1;}
随时随地看视频慕课网APP
我要回答