【问题标题】:How can I get a variables "full path"?如何获得变量“完整路径”?
【发布时间】:2019-07-19 20:03:26
【问题描述】:

所以说我有课。我希望能够获得基于类层次结构的变量完整路径

class A {
   string a {get; set;}
}

class B {
   A a {get; set;}
}

class C {
   B b {get; set}
}

class Main {
   static void main(string[] args){
      C c = new C();
      var path = GetPath(c=>c.b.a);          
   }

   static string GetPath<T>(Expression<Func<T>> prop){
      //So if I have a method which prints the strings full path
      //I want to retrieve as a string "C.B.a"
      //How could I get this path
   }
}

【问题讨论】:

  • 这不是你发给方法的吗? c.b.a?
  • 如果你能澄清你为什么想要达到的目标,而不是有人可以提供帮助......显然没有办法完全按照你的要求去做 - getPath(42) ??? (您可能想研究类似于 Moq 使用它们的表达式树)
  • @AAA 我希望它是大写的(类名)
  • 如果你已经有了路径,为什么还要调用一个方法给你getPath(c.b.a)?你知道它在编译时是c.b.a
  • 试试HtmlHelper.NameFor(c=&gt;c.b.a)

标签: c# asp.net .net asp.net-mvc asp.net-core


【解决方案1】:

我觉得我应该让你知道我不是 Expression 的专家,所以如果你尝试在这个问题上抛出比你的示例更复杂的东西,它很有可能是行不通的.例如,如果您尝试执行以下操作:C.b.GetAnA().a,它将无法正常工作。但是,它可能会给您一个起点,让您自己解决剩下的问题。

static string GetPath<T>(Expression<Func<T>> prop)
{
    var body = prop.Body as System.Linq.Expressions.MemberExpression;
    if (body is null)
    {
        return null;
    }
    string res = body.Member.Name;
    MemberExpression expr = body;
    while ((expr = (expr.Expression as MemberExpression)) != null)
    {
        if (expr.Member is FieldInfo fi)
        {
            res = fi.FieldType.Name + "." + res;
        }
        else if (expr.Member is PropertyInfo pi)
        {
            res = pi.PropertyType.Name + "." + res;
        }
    }
    return res; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2010-11-28
    • 2017-03-16
    相关资源
    最近更新 更多