这个问题与我之前的问题How to get a IDictionary<string, object> of the parameters previous method called in C#有关?. 我写了代码,但仍然缺少一块。如何从参数中获取值?
如果执行以下代码,则输出仅显示参数的名称,而不显示值。
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;
}
}
}