开发者

Need something like locals in python

It works like that:

>>> def foo(arg)开发者_开发知识库: 

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

And i need something like this in c# .net, or how is it possible to implement it myself?


This is not possible. The other answers have given you ideas on how you can retrieve the set of local variables and their types, but certainly not their current values at time of execution. There is no provision for this in C# or .NET. The same goes for method parameters: you can retrieve their types (and even their names), but not their values.

Please allow me to suggest that if you need this, your code design is severely flawed. You should consider rethinking your code structure.

As a workaround, you could declare a class which has fields instead of the locals 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 see that this is not very robust code: any time you make a change to that class, implicit assumptions you made in this code snippet might break.

The standard, recommended way to pass associative data around in C# is a Dictionary<,>. This is the equivalent to Python’s dict. You can use a Dictionary<string, object> if you need names as keys and arbitrary objects as values, but you will benefit from compile-time validity checks if you use a more specific type than object.


Try poking around the Reflection classes, in particular LocalVariableInfo - although the variable names are not preserved, so it is not exactly what you want.


I think 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 calling method's body, so this can be used in its own function you can use the StackFrame class:

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

However this approach is brittle since usage of StackFrame depends on things like optimisations and method inlining.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜