【问题标题】:Method chains with nameof operator带有 nameof 运算符的方法链
【发布时间】:2015-10-27 15:37:32
【问题描述】:

如果我执行nameof(instance.SomeProperty),它的计算结果为"SomeProperty"

有什么办法可以得到整个方法链"instance.SomeProperty"

我知道我可以做到nameof(instance) + "." + nameof(instance.SomeProperty),但有没有更好的更易于维护的方法?

【问题讨论】:

  • $"{nameof(instance)}.{nameof(instance.SomeProperty)}"
  • 这并不真正属于nameof的预期目的范围

标签: c# c#-6.0


【解决方案1】:

有什么办法可以得到整个方法链“instance.SomeProperty”?

不。但是,您可以执行与其他解决方案类似的操作:

$"{nameof(instance)}.{nameof(instance.SomeProperty)}"

你可以试试here

【讨论】:

    【解决方案2】:

    不,没有。 nameof 运算符仅在表达式末尾产生属性(或类、字段等),因此 nameof(Program.Main) 将产生 Mainnameof(ConsoleAppliation1.Program.Main) 也是如此。

    nameof 运算符并不是要按照您的要求进行。它只是防止传递依赖于属性/类名的唯一名称的事件处理程序、依赖属性等的名称。你想做的所有其他花哨的事情都是你自己做的。

    就像M.kazem Akhgary 评论的那样,您可以通过自己构建表达式来自己做到这一点:

    $"{nameof(instance)}.{nameof(instance.SomeProperty)}"
    

    【讨论】:

      【解决方案3】:

      我的 5 美分:

      using System;
      using System.Linq.Expressions;
      
      public static class Program {
          public static void Main() {
              Console.WriteLine(Name.Of<A>(x => x.B.Hehe)); // outputs "B.Hehe"
      
              var a = new A();
              Console.WriteLine(Name.Of(() => a.B.Hehe));   // outputs "B.Hehe"
          }
      
          public class A {
              public B B { get; } // property
          } 
      
          public class B {
              public int Hehe; // or field, does not matter
          } 
      }
      
      public static class Name 
      {
          public static string Of(this Expression<Func<object>> expression) => Of(expression.Body);
      
          public static string Of<T>(this Expression<Func<T, object>> expression) => Of(expression.Body);
      
          public static string Of(this Expression expression)
          {
              switch (expression)
              {
                  case MemberExpression m:                
                      var prefix = Of(m.Expression);
                      return (prefix == "" ? "" : prefix + ".") + m.Member.Name;
                  case UnaryExpression u when u.Operand is MemberExpression m:
                      return Of(m);
                  default:
                      return "";
              }
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 2016-08-15
        • 1970-01-01
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 2016-02-22
        • 2020-11-10
        • 2013-04-11
        • 2023-01-13
        相关资源
        最近更新 更多