是否可以通过反射获得局部变量? [英] Is it possible to get local variables through reflection?

查看:269
本文介绍了是否可以通过反射获得局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法至少有50个局部变量。我需要从字符串值中选择一个变量。是否可以访问具有C#反射的局部变量?



编辑

  ()
{
var a1 = List< MyClass>();
var a2 = List< MyClass>();
var a3 = List< MyClass>();
var a4 = List< MyClass>();
var a5 = List< MyClass>();
........................
.................. ......
........................
//我在运行时找到一个字符串值。可能的值是a1,a2,a3,a4,a5,....我需要选择一个
}


解决方案

真正的答案,没有。



编辑OP后:确定没有。在编译时会丢弃这些名称



你可以得到IL指令,虽然(Method.Body)。



使用Cecil Decompiler来猜测变量是什么(虽然没有名字)。但是,通常很难从变量中区分(重用)temps,并且所有的语法糖都丢失了



另外:修改你的代码和其他注释一样:)


I have a method with at least 50 local variables. I need to select a variable from a string value. Is it possible to access a local variable with C# reflection?

Edit:

void A()
{
    var a1 = List<MyClass>();
    var a2 = List<MyClass>();
    var a3 = List<MyClass>();
    var a4 = List<MyClass>();
    var a5 = List<MyClass>();
    ........................
    ........................
    ........................
    // I have a string value found at runtime. The possible values of it are a1,a2,a3,a4,a5,.... I need to select one
}

解决方案

Real answer, no.

After edited OP: Definite no. The names are 'discarded' at compile time

You can get at the IL instructions, though (Method.Body).

Use Cecil Decompiler to 'guess' what would be variables (no names, though). However, it will be generally hard to distinguish (reused) temps from variables and all syntactic sugar is lost

Also: fix your code like the other comments say :)

这篇关于是否可以通过反射获得局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆