Is there any way for the nameof operator to access method parameters (outside of the same method)?

血红的双手。 提交于 2020-02-01 09:52:25

问题


Take the following class and method:

public class Foo
    public Foo Create(string bar) {
        return new Foo(bar);
    }

So getting "Create" is obvious: nameof(Foo.Create)

Is there any way to get "bar" other than using reflection to read the parameters at run time?


回答1:


No. There is no way to get the parameter names from the outside of the method using nameof. nameof doesn't work for method parameters if you want the name on the calling side (for the callee it does work obviously). The other methods you mentioned, like reflection, do work.

var parameterNames = typeof(Program)
                     .GetMethod(nameof(Program.Main)).GetParameters()
                     .Select(p => p.Name);



回答2:


I know this is a late reply, but I have found a fairly simple and reasonably elegant solution to the problem that doesn't require reflection.

Modify class Foo like this...

public class Foo
  public static string CreateName = nameof(Create);
  public Foo Create(string bar) {
    return new Foo(bar);
  }
}

...then in other classes you can do...

Foo.CreateName

...which will give you the name of the method.



来源:https://stackoverflow.com/questions/37350104/is-there-any-way-for-the-nameof-operator-to-access-method-parameters-outside-of

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