Access a methods local variable value using a stri

2019-05-26 08:00发布

问题:

I am attempting to get the value of a variable that has been declared locally in a method based on a string containing the variables name. I have been trying to use reflection as posted in multiple SO threads. The name of the variable is being stored in a table and accessed in the same method.

The problem I am having is seeing the methods local variable or the Method itself for that matter. I can see that value of a global variable as indicated in the code snippet below but I can not find the local variable in my methods. In other words the the variable TestrecordType is declared as a class variable and I can access it in any method wusing the code below. I need to access the variables in the local method where the code lives. Can anyone help me drill down to the methods level? Is it possible?

//10.07.2013 DRowe Collecting data for the json class
Corporate_Record clsCorporateRecord = new Corporate_Record();

// get the mapping for the class
ABC.Services.SYS.BmsBoardingEntryLayoutSpecificationCollection colLayoutSpecs = new ABC.Services.SYS.BmsBoardingEntryLayoutSpecificationCollection();
colLayoutSpecs = ABC.Services.SYS.BmsBoardingEntryLayoutSpecification.GetBySubClass("Corporate_Record");
foreach (ABC.Services.SYS.BmsBoardingEntryLayoutSpecification SpecRecord in colLayoutSpecs) {

    // Alter main class level (Global) variable
    TestrecordType = TestrecordType + " Now";

    string myproperty = SpecRecord.FieldName ;
    string myVariable = SpecRecord.MapToCodeVariable;
    string myType = SpecRecord.Type;

    // Can grab Main class variable values but not the local method variable values
    var result = this.GetType().GetField("TestrecordType").GetValue(this);

    clsCorporateRecord.GetType().GetProperty(myproperty).SetValue(clsCorporateRecord, result, null);

    MethodInfo mInfo = typeof(Worker).GetMethod("CreateCorporateRecord01");                         
}                    
myCollection.Corporate_Record.Add(clsCorporateRecord);
//10.07.2013 DRowe END

回答1:

Local variables aren't representing in reflection. You can see globals because they're members of a type. Locals, however, are just slots on the current stack, and that stack isn't exposed to the reflection APIs.

The only place that the call stack is exposed programmatically is in the stack trace in an exception. You could throw an exception deliberately, catch it, and pick through the stack trace. But it would be a bad, bad, idea, and extremely slow.