C#:如何通过存储在字符串中的名称获取对象? [英] C#: how to get an object by the name stored in String?

查看:10
本文介绍了C#:如何通过存储在字符串中的名称获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 中按名称获取对象?

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

即使用

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

推荐答案

不,不是.

对象没有名字——变量有.一个对象可以被任意数量的变量引用:零、一个或多个.

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

可以做的是按名称获取字段(静态或实例变量)(使用 Type.GetField) 并获取这些字段的值(对于特定实例,如果您使用实例变量).

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天全站免登陆