我希望能够以前一个方法的IDictionary<string, object>
形式获取参数列表。有一个问题:即使它是免费的,我也无法使用第三方面向方面编程框架。
例如:
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!");
}
}
}
有任何建议或想法吗?如有必要,请随意使用反射。
答案 0 :(得分:2)
我认为没有AOP你能做的最好就是使用StackFrame并获得被调用的方法。
我想这会需要太多的开销。如果你传入了你修改过的变量怎么办?在方法中修改原始值之前,您必须分配额外的空间来存储原始值。这可能会很快失控
答案 1 :(得分:2)
您可以使用StackTrace
来满足您的所有需求:
var trace = new System.Diagnostics.StackTrace();
var frame = trace.GetFrame(1); //previous
var method = frame.GetMethod();
现在你有一个MethodBase个实例。
您可以通过以下方式获取姓名:
var method = method.Name;
例如:
var dict = new Dictionary<string, object>();
foreach (var param in method.GetParameters())
{
dict.Add(param.Name, param.DefaultValue);
}