带有 nameof 运算符的方法链

Method chains with nameof operator

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

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

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

Is there any way I can get the entire method chain "instance.SomeProperty"?

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

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

你可以试试here.

不,没有。 nameof 运算符仅在表达式末尾生成 属性(或 class、字段等),因此 nameof(Program.Main) 将生成 Main,依此类推nameof(ConsoleAppliation1.Program.Main).

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

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

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

我的 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 "";
        }
    }
}