亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有更好的方法將虛線路徑作為字符串?

有沒有更好的方法將虛線路徑作為字符串?

C#
慕蓋茨4494581 2021-10-09 19:45:49
有沒有更好的方法將虛線路徑變成字符串?//I can do something ugly like$"{nameof(obj)}.{nameof(obj.RelatedObj)}.{nameof(obj.RelatedObj.Field)}";我在為這個問題尋找更好的解決方案時遇到了問題。
查看完整描述

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;

}


查看完整回答
反對 回復 2021-10-09
  • 2 回答
  • 0 關注
  • 202 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號