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-代碼 –