2011-12-29 52 views
4

考慮這段JavaScript代碼片段:一般的,集中式的參數記錄儀方法,在C#

Object.prototype.log = function() { 
    // here, you have a centralized place to do logging stuff; 
    console.log(this); 
} 

function fullName(firstName, lastName) 
{ 
    // here, using a simple one-line code, you can log all parameters; 
    arguments.log(); 
} 

fullName('saeed', 'nemati'); 

我們可以有記錄傳遞給方法的所有參數,在C#中類似的機制?

注意:我所做的一切是使用反射,但沒有成功:

public static void LogParameters(this ParameterInfo[] parameters) 
{ 
    StringBuilder builder = new StringBuilder(); 
    builder.Append("*****************\r\n"); 
    builder.Append("Parameters\r\n"); 
    parameters.ToList().ForEach(pi => 
    { 
     builder.AppendFormat("{0} => {1}\r\n", pi.Name, pi.DefaultValue); 
     // The problem is that, I can't get the value of the parameter here 
    }); 
    builder.Append("*****************"); 
    Log.Write(builder.ToString()); 
} 

public string GetFullName(string firstName, string lastName) 
{ 
    MethodBase.GetCurrentMethod().GetParameters().LogParameters(); 
    return firstName + " - " + lastName; 
} 

GetFullName("saeed", "neamati"); 

回答

7

沒有,你可以使用反射無法獲得的參數值。您必須將它們明確地傳遞給日誌記錄方法。

您可以使用調試器API來做到這一點,但您可能不想。如果我是你,我會明確地做到這一點 - 事實上,這很可能最終會帶來更有用的日誌記錄,因爲您只能記錄重要的內容,並在消息中給出一些上下文。

+0

多可悲,多麼糟糕。 AMAIK,PHP也有一個'arguments'對象。我不知道。如果我能做到這一點,通過查看傳遞給它們的參數的值,我可以更靈活地排除實時應用程序問題,同時,我不應該爲每種方法編寫多行代碼。 :( – 2011-12-29 08:40:36

+0

@SaeedNeamati:如果你正在解決一個實時應用程序,你通常需要*目標*記錄,解釋上下文和*相關*參數。我個人認爲我不認爲它有用 – 2011-12-29 08:46:22

+0

是啊,你是對的,但很多時候(有時候並非如此))我真的厭倦了寫許多代碼來記錄某些東西。例如,我們已經有了一個處理類型** Exception **的擴展方法,我們只需使用'ex.Handle();'來記錄我們的異常,這當然是優雅,簡潔,集中,開發者友好等等。 :) – 2011-12-29 08:52:45