Is there a way to get an array of the arguments passed to a method?

后端 未结 9 1260
小蘑菇
小蘑菇 2020-12-05 18:17

Say I have a method:

 public void SomeMethod(String p1, String p2, int p3)
 {

 #if DEBUG
    object[] args = GetArguments();
    LogParamaters(args);
 #endi         


        
相关标签:
9条回答
  • 2020-12-05 18:40

    As long as you know what types to expect you could log them in an SQL database. Write a method that does a type check, and then fills the appropriate DB column with the parameter (argument) value. If you have a custom type then you can use the type name and save that as string in it's own special column.

    -Edit

    Also, using the MethodBase.Name extension method, you could associate your parameters with the method that took them as arguments as mentioned in another post below. Be a handy way of keeping track of all methods used, and with which arguments, and of which type.

    Is this even vaguely a good idea? :)

    0 讨论(0)
  • 2020-12-05 18:44

    Well, if you just want to pass the values, you can cheat and define an object array:

    public static void LogParameters(params object[] vals)
    {
    
    }
    

    This will incur boxing on value types and also not give you any parameter names, however.

    Say I have a method:

     public void SomeMethod(String p1, String p2, int p3) 
     { 
    
     #if DEBUG 
        LogParamaters(p1, p2, p3); 
     #endif 
    
         // Do Normal stuff in the method 
     } 
    

    Update: unfortunately reflection will not do it all automatically for you. You will need to provide the values, but you can use reflection to provide the param names/types:

    How can you get the names of method parameters?

    So the method sig would change to something like:

    public static void LogParameters(string[] methodNames, params object[] vals)
    { }
    

    Then you can enforce/assume that each index in each collection tallies, such that methodNames[0] has the value vals[0].

    0 讨论(0)
  • 2020-12-05 18:46

    Well params help with the log call, but won't help the existing method signatures. Logging using an AOP framework might be a more productive approach?

    0 讨论(0)
提交回复
热议问题