2

我需要在十几个函数中记录所有函数参数。

有没有办法以编程方式确定所有参数及其值(或至少它们的 .ToString() 值)?也许通过反射?

4

2 回答 2

1

To the best of my knowledge there's no way to use reflection to dynamically list and determine value of local variables. You can use reflection to get type information about the parameters of a method, but only the declared type - you can't automatically get information about the actual arguments, because the reflection metadata gives information about the method definition, not the specific values passed to it at runtime.

You can, however, do something like this:

static class Extensions
{
    public static string GetTypeAndValue(this object obj) 
    { 
        return String.Format("{0}: {1}", obj.GetType().Name, obj.ToString()); 
    }
}

Then, from within each method in which you want to perform logging, do something like

private void SomeMethodToBeLogged(string some_string, int some_int, bool some_bool)
{
    Logger.Log(String.Format("SomeMethodToBeLogged({0}, {1}, {2})", 
        some_string.GetTypeAndValue(), 
        some_int.GetTypeAndValue(), 
        some_bool.GetTypeAndValue()));
}
于 2009-11-20T20:56:27.330 回答