Need something like locals in python

It works like this:

>>> def foo(arg): 

...     x = 1
...     print locals()
...     
>>> foo(7)        
{'arg': 7, 'x': 1}
>>> foo('bar')    
{'arg': 'bar', 'x': 1}

      

And do I need something like this in C # .net, or how can I implement it myself?

+1


source to share


3 answers


It's impossible. The other answers gave you ideas on how you can get a set of local variables and their types, but of course not their current values ​​at runtime. There is no such provision in C # or .NET. The same goes for method parameters: you can get their types (and even their names), but not their values.

Please let me assume that if you need it your code design is badly flawed. You should consider rethinking your code structure.

As a workaround, you can declare a class that has fields, not the locales you want. Then you can use Reflection to iterate over those fields:



foreach (var field in typeof(MyClass).GetFields())
    Console.WriteLine("Field name: {0}; field value: {1}",
        field.Name, field.GetValue(myInstance));

      

However, I think you can easily understand that this is not very robust code: anytime you make changes to this class, the implicit assumptions you make in this piece of code can break.

The standard recommended way to pass associative data in C # is Dictionary<,>

. This is equivalent to Pythons dict

. You can use Dictionary<string, object>

if you want names as keys and arbitrary objects as values, but you will benefit from compile-time validation if you use a more specific type than object

.

+2


source


Try looping through the Reflection classes, in particular LocalVariableInfo - although the variable names are not persisted, so this is not exactly what you want.



+1


source


I think that something like this should work:

MethodBody currentMethodBody = MethodBase.GetCurrentMethod().GetMethodBody();
foreach(LocalVariableInfo local in currentMethodBody.LocalVariables)
{
    Console.WriteLine("Local: {0}", local);
}

      

EDIT: To get the body of the calling method so it can be used in your own function, you can use the class StackFrame

:

MethodBody callingBody = (new StackFrame(1)).GetMethod().GetMethodBody();

      

However, this approach is fragile, as using a StackFrame depends on things like optimization and nesting method.

+1


source







All Articles