实例化对象时以编程方式使用字符串作为对象名称 [英] Programmatically using a string as object name when instantiating an object

查看:53
本文介绍了实例化对象时以编程方式使用字符串作为对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个人为的示例,但可以说我已经声明了对象:

This is a contrived example, but lets say I have declared objects:

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

我有一个字符串数组:

string[] stringarray = new string[] {"foo","bar","baz"};

如何使用字符串数组以编程方式访问和实例化这些对象,并使用诸如foreach之类的方法进行迭代:

How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach:

foreach (string i in stringarray) {
    `i`Obj = new CustomObj(i);
}

希望我试图传达的想法很明确.在C#中可以吗?

Hope the idea I'm trying to get across is clear. Is this possible in C#?

推荐答案

您需要清楚了解对象和变量之间的区别.对象本身没有名称.变量名称在编译时确定.除了通过反射,您不能通过执行时间确定的名称访问变量.

You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection.

听起来您真的只想要一个Dictionary<string, CustomObj>:

Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>();

foreach (string name in stringArray)
{
    map[name] = new CustomObj(name);
}

然后您可以使用索引器访问字典中的对象.

You can then access the objects using the indexer to the dictionary.

如果您确实要在执行时根据变量名设置变量的值,则必须使用反射(请参见

If you're really trying to set the values of variables based on their name at execution time, you'll have to use reflection (see Type.GetField). Note that this won't work for local variables.

这篇关于实例化对象时以编程方式使用字符串作为对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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