我能从当前执行的函数中程序化地获取参数名称/值吗?

44

我想做类似这样的事情:

public MyFunction(int integerParameter, string stringParameter){
    //Do this:
    LogParameters();
    //Instead of this:
    //Log.Debug("integerParameter: " + integerParameter + 
    //          ", stringParameter: " + stringParameter);

}

public LogParameters(){
    //Look up 1 level in the call stack (if possible),
    //Programmatically loop through the function's parameters/values
    //and log them to a file (with the function name as well).
    //If I can pass a MethodInfo instead of analyzing the call stack, great.
}

我甚至不确定我想要做的事情是否可能,但如果能够在运行时自动输出参数名称/值到文件中而无需显式编写记录它们的代码,那将非常好。

这是否可能?


2
接近重复的内容 https://dev59.com/z3VC5IYBdhLWcg3w9GHM - Peter Lillevold
请参考此链接:https://dev59.com/2nRA5IYBdhLWcg3wzhRY - Peter Lillevold
重复的问题 https://dev59.com/MErSa4cB1Zd3GeqPXZPe - Austin Salonen
6个回答

22

我知道有人链接到提到PostSharp的其他问题,但我还是想发布解决我的问题的代码(使用PostSharp),以便其他人能够受益。

class Program {
    static void Main(string[] args) {
        Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
        new MyClass().MyMethod(44, "asdf qwer 1234", 3.14f, true);
        Console.ReadKey();
    }
}
public class MyClass {
    public MyClass() {
    }
    [Trace("Debug")]
    public int MyMethod(int x, string someString, float anotherFloat, bool theBool) {
        return x + 1;
    }
}
[Serializable]
public sealed class TraceAttribute : OnMethodBoundaryAspect {
    private readonly string category;

    public TraceAttribute(string category) {
        this.category = category;
    }

    public string Category { get { return category; } }

    public override void OnEntry(MethodExecutionArgs args) {
        Trace.WriteLine(string.Format("Entering {0}.{1}.", 
                                      args.Method.DeclaringType.Name, 
                                      args.Method.Name), category);

        for (int x = 0; x < args.Arguments.Count; x++) {
            Trace.WriteLine(args.Method.GetParameters()[x].Name + " = " + 
                            args.Arguments.GetArgument(x));
        }
    }

    public override void OnExit(MethodExecutionArgs args) {
        Trace.WriteLine("Return Value: " + args.ReturnValue);

        Trace.WriteLine(string.Format("Leaving {0}.{1}.", 
                                      args.Method.DeclaringType.Name, 
                                      args.Method.Name), category);
    }
} 

Trace属性添加到方法中会导致输出非常好的调试信息,就像这样:

Debug: Entering MyClass.MyMethod. 
x = 44
someString = asdf qwer 1234
anotherFloat = 3.14
theBool = True
Return Value: 45
Debug: Leaving MyClass.MyMethod.

3
使用免费版的PostSharp Express,这是否可行? - Dbl

12

理论上,使用调试版本且关闭优化是可能的,但实际上,我建议您进行一些源代码重写。

有人会告诉你反射可以工作,但实际上不行,因此这里有一个可以获取参数值的函数。它很可能在启用优化时无法可靠地工作(例如,在内联时可能甚至没有堆栈帧),并且安装调试器以便调用该函数将不会像您希望的那样简单。


实际上,优化方面的观点非常好 - 我原以为这个问题与调试工具有关... - Paul Kohler
1
@Ben Voigt - дЅ жњ‰ICorDebugILFrame::GetArgumentзљ„дЅїз”Ёз¤єдѕ‹еђ—пјџ - Paul Kohler
@Ben Voigt - 如果您能提供一个使用示例,我也想看看。感谢您的答案! - Mark Carpenter

9
StackTrace stackTrace = new StackTrace();
ParameterInfo[] parameters = stackTrace.GetFrame(1).GetMethod().GetParameters();

注意,GetFrame(1)获取的是调用方法而不是当前方法。这应该可以给您所需的结果,并允许您在LogParameters()中执行下面的代码。
由于无法从ParameterInfo获取integerParameter和stringParameter的反射值,您需要像下面这样调用LogParameters。
LogParameters(integerParameter, stringParameter);

一定要使用 StackTrace 来获取相关的 StackFrame,这甚至允许在“日志记录”子例程中声明可选的“深度”参数。+1 - M.A. Hanin
更新提供了值,但有几件事可能会出错。首先,这是一个维护负担——参数列表的任何更改都必须在日志调用中重复。其次,如果您的原始函数具有类型为 object[] 的单个参数,则必须跳过一些额外的步骤。 - Ben Voigt

3

除非您使用调试器API,否则无法循环遍历调用堆栈上不同方法的参数值。虽然您可以从调用堆栈中获取参数名称(如其他人所述),但是无法循环遍历参数值。

最接近的方法是:

public MyFunction(int integerParameter, string stringParameter){
    LogParameters(integerParameter, stringParameter);
}

public void LogParameters(params object[] values){
    // Get the parameter names from callstack and log names/values
}

你可以做到,你只需要调试API,而不是反射。 - Ben Voigt
这种方法是一个不错的想法,但有一些事情可能会出错。首先,它是一个维护负担 - 参数列表的任何更改都必须在日志调用中重复。其次,如果您的原始函数具有类型为object[]的单个参数,则必须跳过一些额外的步骤。 - Ben Voigt
1
@BenVoigt - 是的,这就是为什么我现在会使用AOP来做这样的事情。 - Peter Lillevold

3
这是创建日志的实用程序类。
internal class ParamaterLogModifiedUtility
{
    private  String _methodName;
    private String _paramaterLog;

    private readonly JavaScriptSerializer _serializer;
    private readonly Dictionary<String, Type> _methodParamaters;
    private readonly List<Tuple<String, Type, object>>_providedParametars;

    public ParamaterLogModifiedUtility(params Expression<Func<object>>[] providedParameters)
    {
        try
        {
            _serializer = new JavaScriptSerializer();
            var currentMethod = new StackTrace().GetFrame(1).GetMethod();

            /*Set class and current method info*/
            _methodName = String.Format("Class = {0}, Method = {1}", currentMethod.DeclaringType.FullName, currentMethod.Name);

            /*Get current methods paramaters*/
            _methodParamaters = new Dictionary<string, Type>();
            (from aParamater in currentMethod.GetParameters()
             select new { Name = aParamater.Name, DataType = aParamater.ParameterType })
             .ToList()
             .ForEach(obj => _methodParamaters.Add(obj.Name, obj.DataType));

            /*Get provided methods paramaters*/
            _providedParametars = new List<Tuple<string, Type, object>>();
            foreach (var aExpression in providedParameters)
            {
                Expression bodyType = aExpression.Body;

                if (bodyType is MemberExpression)
                {
                    AddProvidedParamaterDetail((MemberExpression)aExpression.Body);
                }
                else if (bodyType is UnaryExpression)
                {
                    UnaryExpression unaryExpression = (UnaryExpression)aExpression.Body;
                    AddProvidedParamaterDetail((MemberExpression)unaryExpression.Operand);
                }
                else
                {
                    throw new Exception("Expression type unknown.");
                }
            }

            /*Process log for all method parameters*/
            ProcessLog();

        }
        catch (Exception exception)
        {
            throw new Exception("Error in paramater log processing.", exception);
        }
    }

    private void ProcessLog()
    {
        try
        {
            foreach (var aMethodParamater in _methodParamaters)
            {
                var aParameter =
                    _providedParametars.Where(
                        obj => obj.Item1.Equals(aMethodParamater.Key) && obj.Item2 == aMethodParamater.Value).Single();
                _paramaterLog += String.Format(@" ""{0}"":{1},", aParameter.Item1, _serializer.Serialize(aParameter.Item3));
            }
            _paramaterLog = (_paramaterLog != null) ? _paramaterLog.Trim(' ', ',') : string.Empty;
        }
        catch (Exception exception)
        {
            throw new Exception("MathodParamater is not found in providedParameters.");
        }
    }

    private void AddProvidedParamaterDetail(MemberExpression memberExpression)
    {
        ConstantExpression constantExpression = (ConstantExpression) memberExpression.Expression;
        var name = memberExpression.Member.Name;
        var value = ((FieldInfo) memberExpression.Member).GetValue(constantExpression.Value);
        var type = value.GetType();
        _providedParametars.Add(new Tuple<string, Type, object>(name, type, value));
    }


    public String GetLog()
    {
        return String.Format("{0}({1})", _methodName, _paramaterLog);
    }

}

使用该工具

class PersonLogic
{
    public bool Add(PersonEntity aPersonEntity, ushort age = 12, String id = "1", String name = "Roy")
    {
        string log =  new ParamaterLogModifiedUtility(() => aPersonEntity, () => age, () => id, () => name).GetLog();
        return true;
    }
}

现在呼叫用法
class Program
{
    static void Main(string[] args)
    {
        try
        {
            PersonLogic personLogic = new PersonLogic();
            personLogic.Add(id: "1", age: 24, name: "Dipon", aPersonEntity: new PersonEntity() { Id = "1", Name = "Dipon", Age = 24 });
        }
        catch (Exception exception)
        {
            Console.WriteLine("Error.");
        }
        Console.ReadKey();
    }
}

结果日志:

        Class = MethodParamatersLog.Logic.PersonLogic, Method = Add("aPersonEntity":{"CreatedDateTime":"\/Date(1383422468353)\/","Id":"1","Name":"Dipon","Age":24}, "age":24, "id":"1", "name":"Dipon")

1

我按照指示创建了这个类:

public static class Tracer
{
    public static void Parameters(params object[] parameters)
    {
        #if DEBUG
            var jss = new JavaScriptSerializer();

            var stackTrace = new StackTrace();

            var paramInfos = stackTrace.GetFrame(1).GetMethod().GetParameters();

            var callingMethod = stackTrace.GetFrame(1).GetMethod();
            Debug.WriteLine(string.Format("[Func: {0}", callingMethod.DeclaringType.FullName + "." + callingMethod.Name + "]"));

            for (int i = 0; i < paramInfos.Count(); i++)
            {
                var currentParameterInfo = paramInfos[i];

                var currentParameter = parameters[i];

                Debug.WriteLine(string.Format("    Parameter: {0}", currentParameterInfo.Name));

                Debug.WriteLine(string.Format("    Value: {0}", jss.Serialize(currentParameter)));
            }
            Debug.WriteLine("[End Func]");
        #endif
    }
}

像这样调用:

public void Send<T>(T command) where T : Command
{
    Tracer.Parameters(command);
}

而输出看起来像这样:
[Func: SimpleCQRS.FakeBus.Send]
    Parameter: command
    Value: {"InventoryItemId":"f7005197-bd20-42a6-b35a-15a6dcc23c33","Name":"test record"}
[End Func]

编辑

.........

我将我的追踪函数扩展以更好地为我服务。要跟踪每个函数及其调用函数等,可以使用StrackTrace.GetFrame(2)来使用添加的功能。现在我的输出更加丰富。我还使用了Json.NET库来输出漂亮格式化的JSON对象。此外,输出可以粘贴到空的JavaScript文件中,查看着色输出。
现在我的输出如下所示:
//Func: HomeController(Constructor): CQRSGui.Controllers.HomeController(Constructor)
//From: RuntimeTypeHandle.CreateInstance: System.RuntimeTypeHandle.CreateInstance
var parameters = {}

//Func: HomeController.Add: CQRSGui.Controllers.HomeController.Add
//From: System.Object lambda_method(System.Runtime.CompilerServices.Closure, System.Web.Mvc.ControllerBase, System.Object[])
var parameters = {
    "name": "car"
}

//Func: Command(Constructor): SimpleCQRS.Command(Constructor)
//From: CreateInventoryItem(Constructor): SimpleCQRS.CreateInventoryItem(Constructor)
var parameters = {}

//Func: CreateInventoryItem(Constructor): SimpleCQRS.CreateInventoryItem(Constructor)
//From: HomeController.Add: CQRSGui.Controllers.HomeController.Add
var parameters = {
    "inventoryItemId": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
    "name": "car"
}

//Func: FakeBus.Send: SimpleCQRS.FakeBus.Send
//From: HomeController.Add: CQRSGui.Controllers.HomeController.Add
var parameters = {
    "command": {
        "InventoryItemId": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
        "Name": "car"
    }
}

//Func: InventoryCommandHandlers.Handle: SimpleCQRS.InventoryCommandHandlers.Handle
//From: FakeBus.Send: SimpleCQRS.FakeBus.Send
var parameters = {
    "message": {
        "InventoryItemId": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
        "Name": "car"
    }
}

//Func: AggregateRoot(Constructor): SimpleCQRS.AggregateRoot(Constructor)
//From: InventoryItem(Constructor): SimpleCQRS.InventoryItem(Constructor)
var parameters = {}

//Func: InventoryItem(Constructor): SimpleCQRS.InventoryItem(Constructor)
//From: InventoryCommandHandlers.Handle: SimpleCQRS.InventoryCommandHandlers.Handle
var parameters = {
    "id": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
    "name": "car"
}

//Func: Event(Constructor): SimpleCQRS.Event(Constructor)
//From: InventoryItemCreated(Constructor): SimpleCQRS.InventoryItemCreated(Constructor)
var parameters = {}

//Func: InventoryItemCreated(Constructor): SimpleCQRS.InventoryItemCreated(Constructor)
//From: InventoryItem(Constructor): SimpleCQRS.InventoryItem(Constructor)
var parameters = {
    "id": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
    "name": "car"
}

//Func: AggregateRoot.ApplyChange: SimpleCQRS.AggregateRoot.ApplyChange
//From: InventoryItem(Constructor): SimpleCQRS.InventoryItem(Constructor)
var parameters = {
    "event": {
        "Id": "d974cd27-430d-4b22-ad9d-22ea0e6a2559",
        "Name": "car",
        "Version": 0
    }
}

强大,不是吗?我只需要查看输出,不需要一次又一次地破坏应用程序,也不需要检查观察和本地窗口。我喜欢这种方式。我已经在我的应用程序中到处放置了tracker.Parameters函数,并且现在自动调试了应用程序。
我添加到输出函数中的一个东西是对序列化错误事件的调用。并从Json.NET处理它。实际上,您可能会遇到循环引用错误。我捕获了它。如果有更多的序列化错误,你也可以捕获它们,然后在参数对象输出下方显示序列化错误。

1
这种方法是一个不错的想法,但有一些事情可能会出错。首先,它是一个维护负担 - 参数列表的任何更改都必须在日志调用中重复。其次,如果您的原始函数具有类型为“object []”的单个参数,则必须跳过一些额外的步骤。 - Ben Voigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接