获取扩展方法中第一个参数的名称?

Ben*_*min 7 .net c# reflection extension-methods stack-frame

string thing = "etc";
thing = thing.GetName();
//now thing == "thing"
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?

public static string GetName(this object obj)
{
    return ... POOF! //should == "thing"
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*pey 5

我同意@Reed的回答。但是,如果您确实要实现此功能,则可以进行以下工作:

string thing = "etc";
thing = new{thing}.GetName();
Run Code Online (Sandbox Code Playgroud)

GetName扩展方法只会使用反射来抓住从匿名对象的第一属性的名称。

唯一的其他方法是使用Lambda表达式,但是代码肯定会复杂得多。


Ree*_*sey 4

不。在您使用它时,“名称”将是“obj” - 可以通过MethodBase.GetCurrentMethod()检索它(使用适当的调试符号) 。GetParameters() [0].名称。

但是,您无法从调用方法中检索变量名称。