private void Method1()
{
//Do something
Log("Something","Method1");
}
private void Method2()
{
//Do something
Log("Something","Method2");
}
private void Log(string message, string method)
{
//Write to a log file
Trace.TraceInformation(message + "happened at " + method);
}
我有几个方法像上面的Method1和Method2,我想通过方法的名称作为参数,而不需要手动编辑代码的方式。传递方法的名称作为参数
这可能吗?
有一个称为['CallerMemberNameAttribute'](http://msdn.microsoft.com/zh-cn/library/system.runtime.compilerservices.callermembername属性)的新属性(我认为在4.5中,需要最新的编译器) (v = vs.110).aspx)完成这个,但是在编译时使用字符串文字。或者,您可以使用linq表达式并查询表达式本身的名称,这通常是为'INotifyPropertyChanged'等属性完成的。 –
而不是传递方法名称,您可以使用反射 –
请参阅http://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-代码 –