Can I get parameter names/values procedurally from the currently executing function?

后端 未结 6 1375
猫巷女王i
猫巷女王i 2020-12-02 14:38

I would like to do something like this:

public MyFunction(int integerParameter, string stringParameter){
    //Do this:
    LogParameters();
    //Instead of         


        
6条回答
  •  庸人自扰
    2020-12-02 14:44

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

    Note, GetFrame(1) gets the calling method rather than the current method. This should give you your desired results and allow you to execute the code below in LogParameters().

    You would need to call LogParameters like below since you wouldn't be able to get the reflected values of integerParameter and stringParameter from ParameterInfo.

    LogParameters(integerParameter, stringParameter);
    

提交回复
热议问题