How to get the IDictionary <string, object> parameters of the previous method called in C #?
I would like to get a list of parameters in the form of the IDictionary<string, object>previous method called. There is one catch: I cannot use a third-party platform for oriented programming, even when it is free.
For instance:
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Question {
internal class Program {
public static void Main(string[] args) {
var impl = new Implementation();
impl.MethodA(1, "two", new OtherClass { Name = "John", Age = 100 });
}
}
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);
// keyValuePair.Value may return a object that maybe required to
// inspect to get a representation as a string.
}
private static IDictionary<string, object> GetParametersFromPreviousMethodCall() {
throw new NotImplementedException("I need help here!");
}
}
}
Any suggestion or ideas? Feel free to use reflection if necessary.
+5
2 answers
You can use StackTraceto get everything you need:
var trace = new System.Diagnostics.StackTrace();
var frame = trace.GetFrame(1); //previous
var method = frame.GetMethod();
You now have an instance of MethodBase .
You can get the name by:
var method = method.Name;
and parameters MethodBase.GetParameters.
For instance:
var dict = new Dictionary<string, object>();
foreach (var param in method.GetParameters())
{
dict.Add(param.Name, param.DefaultValue);
}
+2