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

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

问题描述

这是一个人为的例子,但可以说我有声明的对象:

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

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

和我有一个字符串数组:

And I have an string array:

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



我如何编程访问和使用字符串数组,迭代使用类似一个foreach实例化的对象:

How can I programatically 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.

这听起来像你的真正的只想字典<字符串,CustomObj>

It sounds like you really just want a 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.

如果你真的想设置的变量的基础上在执行时他们的名字的价值,你将不得不使用反射(见的Type.GetField )。请注意,这不会为局部变量工作。

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