This question is related to my previous question How to get a IDictionary<string, object> of the parameters previous method called in C#?. I wrote the code, but there is still a missing piece. How do I get the values from the parameters?
If the following code is executed, the output only shows the parameter's names, but not the values.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Question {
internal class Program {
public static void Main(string[] args) {
var impl = new Implementation();
var otherClass = new OtherClass { Name = "John", Age = 100 };
impl.MethodA(1, "two", otherClass);
}
}
internal class Implementation {
public void MethodA(int param1, string param2, OtherClass param3) {
Logger.LogParameters();
}
}
internal class OtherClass {
public string Name { get; set; }
public int Age { get; set; }
}
internal class Logger {
public static void LogParameters() {
var parameters = GetParametersFromPreviousMethodCall();
foreach (var keyValuePair in parameters)
Console.WriteLine(keyValuePair.Key + "=" + keyValuePair.Value);
}
private static IDictionary<string, object> GetParametersFromPreviousMethodCall() {
var stackTrace = new StackTrace();
var frame = stackTrace.GetFrame(2);
var method = frame.GetMethod();
var dictionary = new Dictionary<string, object>();
foreach (var parameterInfo in method.GetParameters())
dictionary.Add(parameterInfo.Name, parameterInfo.DefaultValue);
return dictionary;
}
}
}