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

后端 未结 9 1320
小蘑菇
小蘑菇 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: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].

提交回复
热议问题