C # obtain Caller information,
When a log component is used, the caller information is often recorded. The caller information is usually obtained through reflection. However,. Net 4.5 introduces three new features: CallerFilePathAttribute, CallerLineNumberAttribute, and CallerMemberNameAttribute. These three features can only be applied to parameters and can only be used in applications and optional parameters. The concept is very simple: if the call point does not provide real parameters, the compiler can use the current file, number of lines, or member name as the real parameter, instead of using the regular default value. If the caller provides real parameters, the compiler ignores these features.
1 class ProgramCallerLineNumberAttribute 2 {3 static void Main (string [] args) 4 {5 Log. logWrite ("test"); 6 Console. readKey (); 7} 8} 9 10 class Log11 {12 public static void LogWrite (string logInfo, 13 [CallerFilePath] string file = null, 14 [CallerLineNumber] int line = 0, 15 [CallerMemberName] string member = null16) 17 {18 Console. writeLine (logInfo); 19 Console. writeLine (file); 20 Console. writeLine (line); 21 Console. writeLine (member); 22 23} 24}