Method chains with nameof operator

﹥>﹥吖頭↗ 提交于 2020-04-07 04:26:45

问题


If I do nameof(instance.SomeProperty), it evaluates to "SomeProperty".

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

I know I could do nameof(instance) + "." + nameof(instance.SomeProperty), but is there a better way that's more maintainable?


回答1:


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

Nope. You can, however, do something similar to your other solution:

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

You can try it here.




回答2:


No, there is not. The nameof operator just yields the property (or class, field, etc) at the end of the expression, so nameof(Program.Main) will yield Main, and so does nameof(ConsoleAppliation1.Program.Main).

The nameof operator wasn't meant to do what you ask. It is just prevent passing names around for event handlers, dependency properties, etc. that depend on the sole name of the property / class name. All other fancy stuff you want to do is on your own.

Like M.kazem Akhgary commented, you can do this yourself by constructing the expression yourself:

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



回答3:


My 5 cents:

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



来源:https://stackoverflow.com/questions/33372247/method-chains-with-nameof-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!