需要像在Python当地人 [英] Need something like locals in python

查看:110
本文介绍了需要像在Python当地人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是这样工作的:

>>> def foo(arg): 

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

和我需要这样的东西在C#.NET或怎么可能实现它自己?

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

推荐答案

这是不可能的。其他答案给你,你如何找回组局部变量及其类型的想法,但肯定不是他们的当前值在执行的时间。没有为此在C#.NET或没有规定。这同样适用于方法的参数:你可以检索它们的类型(甚至是自己的名字),而不是它们的值

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.

请允许我建议,如果你需要,你的code设计严重缺陷。你应该考虑重新思考你的code结构。

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));

不过,我认为你可以很容易地看到,这是不是很强大的code:任何时候你做出改变这个类,你在这个code段可能会破坏发隐含假设

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.

标准的,推荐的方式在C#中来回传递关联数据是词典<,> 。这相当于Python的字典。您可以使用词典<字符串,对象> 如果你需要的名字作为键和任意对象作为其值,但是会从编译时的有效性检查,如果您使用的是更受益具体类型而不是对象

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.

这篇关于需要像在Python当地人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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