C#:如何让一个物体被存储在字符串的名字吗? [英] C#: how to get an object by the name stored in String?

查看:130
本文介绍了C#:如何让一个物体被存储在字符串的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在C#中通过名字得到一个对象?

即。得到this.obj0使用

 字符串对象名=obj0;
executeSomeFunctionOnObject(this.someLoadObjectByName(对象名));
 

解决方案

没有,不是这样的。

对象没有名字 - 变量做。一个目的可以通过任何数量的变量被引用:零个,一个或多个

您的什么的事,然而,是名得到字段(静态或实例变量)(使用<一个href="http://msdn.microsoft.com/en-us/library/system.type.getfield.aspx"><$c$c>Type.GetField)并获得这些字段的值(具体举例来说,如果你使用的实例变量)。

根据你想要做什么,你可能还需要考虑名称的字典对象。

is it possible in C# to get an object by name?

i.e. get this.obj0 using

string objectName = "obj0";
executeSomeFunctionOnObject(this.someLoadObjectByName(objectName));

解决方案

No, it's not.

Objects don't have names - variables do. An object may be referenced by any number of variables: zero, one or many.

What you can do, however, is get fields (static or instance variables) by name (using Type.GetField) and get the values of those fields (for a specific instance, if you're using instance variables).

Depending on what you're trying to do, you might also want to consider a dictionary from names to objects.

这篇关于C#:如何让一个物体被存储在字符串的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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