使用包含.Net中变量名称的字符串访问方法局部变量值

我试图获取已在基于包含变量名称的字符串的方法中本地声明的变量的值。 我一直在尝试使用多个SO线程中发布的reflection。 变量的名称存储在表中,并以相同的方法访问。

我遇到的问题是看到方法局部变量或方法本身。 我可以看到下面的代码片段中指出的全局变量的值,但我在我的方法中找不到局部变量。 换句话说,变量TestrecordType被声明为类变量,我可以在任何方法中使用下面的代码来访问它。 我需要访问代码所在的本地方法中的变量。 任何人都可以帮助我深入到方法级别吗? 可能吗?

//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 

局部变量不代表reflection。 你可以看到全局变量,因为它们是一个类型的成员。 但是,本地只是当前堆栈上的插槽,并且该堆栈不会暴露给reflectionAPI。

以编程方式公开调用堆栈的唯一位置是exception中的堆栈跟踪。 你可以故意抛出exception,抓住它,然后挑选堆栈跟踪。 但这将是一个坏的,坏的,想法,而且非常缓慢。