string thing = "etc";
thing = thing.GetName();
//now thing == "thing"
Is this even possible?
public static string GetName(this object obj)
{
return ... POOF! //should == "thing"
}
string thing = "etc";
thing = thing.GetName();
//now thing == "thing"
Is this even possible?
public static string GetName(this object obj)
{
return ... POOF! //should == "thing"
}
我同意@Reed 的回答。但是,如果你真的想实现这个功能,你可以让它工作:
string thing = "etc";
thing = new{thing}.GetName();
扩展方法将GetName
简单地使用反射从匿名对象中获取第一个属性的名称。
唯一的另一种方法是使用 Lambda 表达式,但代码肯定会复杂得多。
不。在您使用它时,“名称”将是“obj” - 这可以通过MethodBase.GetCurrentMethod() 检索(带有调试符号)。GetParameters() [0].名称。
但是,您无法从调用方法中检索变量名称。
如果您需要扩展方法中的原始变量名,我认为最好这样做:
thing.DoSomething(nameof(thing));
public static string DoSomething(this object obj, string name) {
// name == "thing"
}
C# 6 中的新nameof()
功能将完全取代扩展方法。
if (x == null) throw new ArgumentNullException(nameof(x)); WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode”
有点相关的是CallerMemberAttribute
which 将获取调用函数的方法的名称。这两种方法的有用比较,以及与PropertyChanged
事件相关的示例,还讨论了生成的 IL 代码(TL;DR:它们是相同的)。