Finding the variable name passed to a function

前端 未结 17 2164
广开言路
广开言路 2020-11-22 04:11

Let me use the following example to explain my question:

public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = "         


        
17条回答
  •  萌比男神i
    2020-11-22 04:49

    Yes! It is possible. I have been looking for a solution to this for a long time and have finally come up with a hack that solves it (it's a bit nasty). I would not recommend using this as part of your program and I only think it works in debug mode. For me this doesn't matter as I only use it as a debugging tool in my console class so I can do:

    int testVar = 1;
    bool testBoolVar = True;
    myConsole.Writeline(testVar);
    myConsole.Writeline(testBoolVar);
    

    the output to the console would be:

    testVar: 1
    testBoolVar: True
    

    Here is the function I use to do that (not including the wrapping code for my console class.

        public Dictionary nameOfAlreadyAcessed = new Dictionary();
        public string nameOf(object obj, int level = 1)
        {
            StackFrame stackFrame = new StackTrace(true).GetFrame(level);
            string fileName = stackFrame.GetFileName();
            int lineNumber = stackFrame.GetFileLineNumber();
            string uniqueId = fileName + lineNumber;
            if (nameOfAlreadyAcessed.ContainsKey(uniqueId))
                return nameOfAlreadyAcessed[uniqueId];
            else
            {
                System.IO.StreamReader file = new System.IO.StreamReader(fileName);
                for (int i = 0; i < lineNumber - 1; i++)
                    file.ReadLine();
                string varName = file.ReadLine().Split(new char[] { '(', ')' })[1];
                nameOfAlreadyAcessed.Add(uniqueId, varName);
                return varName;
            }
        }
    

提交回复
热议问题