-1

How can I user reflection to get the fields inside a method? I tried to use the MethodInfo and then GetFields but the values returned are not the fields I defined within the method.

For example, using the code below, how would I get the FieldInfo for LineNo?

    private void MyMethod()
    {
        int LineNo = 0;
    }

Thanks

j2associates
  • 1,115
  • 10
  • 19
  • 1
    Why do you want that? – mjwills Sep 08 '20 at 12:09
  • Reading an input csv file, parsing it and then creating an output csv file. The output file column headers are based on an enum. I wanted to use the enum Names collection and then assign like named local variables.I never tried to do this at the method level before. It's always good to be edumacated :-). – j2associates Sep 08 '20 at 14:41
  • 1
    If you want data from a method, then return this data. – ckuri Sep 08 '20 at 16:47
  • Short answer : you can't. what's inside the method is IL code, it can't be described in terms of "fields". Medium answer : this code can be decompiled using lib like roslyn. Long answer : this would probably be huge overkill given the task you described (and that I still don't have understood). Any decent csv parser generator lib will let you access columns by name. So there is probably not need for naming local var. – v1nce Jul 12 '22 at 17:49

2 Answers2

0
  1. These are not fields but local variables.
  2. At best you can get IL of method body. If you can somehow parse that you should be able to get your hands at all the locals declared in the method.
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
0

With reflection you can't get values of field in code of function,

You can get the values of field of Class/Object.

Ygalbel
  • 5,214
  • 1
  • 24
  • 32