C# 在循环中动态创建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10930705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating objects dynamically in loop
提问by user469453
I have an array of strings that I am looping through. I would like to loop through the array and on each iteration, create a new object with a name that matches the string value.
我有一个循环遍历的字符串数组。我想遍历数组并在每次迭代中创建一个名称与字符串值匹配的新对象。
For example;
例如;
string[] array = new string[] { "one", "two", "three" };
class myClass(){
public myClass(){
}
}
foreach (string name in array)
{
myClass *value of name here* = new myClass();
}
Would result in three objects being instantiated, with the names "one", "two" and "three".
将导致实例化三个对象,名称为“一”、“二”和“三”。
Is this possible or is there are better solution?
这是可能的还是有更好的解决方案?
采纳答案by Michael Buen
What are you trying to do is not possible in statically-typed language. IIRC, that's possible on PHP, and it's not advisable though.
你想做什么在静态类型语言中是不可能的。IIRC,这在 PHP 上是可能的,但不建议这样做。
Use dictionary instead: http://ideone.com/vChWD
改用字典:http: //ideone.com/vChWD
using System;
using System.Collections.Generic;
class myClass{
public string Name { get; set; }
public myClass(){
}
}
class MainClass
{
public static void Main()
{
string[] array = new string[] { "one", "two", "three" };
IDictionary<string,myClass> col= new Dictionary<string,myClass>();
foreach (string name in array)
{
col[name] = new myClass { Name = "hahah " + name + "!"};
}
foreach(var x in col.Values)
{
Console.WriteLine(x.Name);
}
Console.WriteLine("Test");
Console.WriteLine(col["two"].Name);
}
}
Output:
输出:
hahah one!
hahah two!
hahah three!
Test
hahah two!
回答by Nikhil Agrawal
While others have given you an alternate but no one is telling why do they recommend you that.
虽然其他人给了你一个替代品,但没有人告诉他们为什么推荐你。
That's because You cannot access object with dynamic names.
那是因为您无法访问具有动态名称的对象。
(Food for thought: Just think for a moment if you could do so, how will you access them before they are even coded/named.)
(深思熟虑:如果可以的话,请想一想,在它们被编码/命名之前,您将如何访问它们。)
Instead create a Dictionary<string, myClass>as others mentioned.
而是Dictionary<string, myClass>像其他人提到的那样创建一个。
回答by Tim Schmelter
Use a Dictionary<String, myClass>instead:
使用 aDictionary<String, myClass>代替:
var dict= new Dictionary<String, myClass>();
foreach (string name in array)
{
dict.Add(name, new myClass());
}
Now you can access the myClassinstances by your names:
现在您可以myClass通过您的名字访问实例:
var one = dict["one"];
or in a loop:
或在循环中:
foreach (string name in array)
{
myClass m = dict[ name ];
}
回答by Oded
Looks like you need a list of dictionary of your objects:
看起来您需要一个对象字典列表:
var myClassDictionary = new Dictionary<string,myClass>();
foreach (string name in array)
{
myClassDicationry.Add(name, new myClass());
}
// usage:
// myClass["one"] <- an instance of myClass
There are no programming languages that I know of that let you define variable names in runtime.
我知道没有任何编程语言可以让您在运行时定义变量名称。
回答by pstrjds
You could do something like this -
你可以做这样的事情 -
Dictionary<string, myClass> classes = new Dictionary<string, myClass>();
foreach(string name in array)
{
classes[name] = new myClass();
}
Then you can refer to the named instances later
然后你可以稍后引用命名实例
classes[name].MyClassMethod();
回答by Asif Mushtaq
You can use the following code.
您可以使用以下代码。
string[] array = new string[] { "one", "two", "three" };
Dictionary<String, myClass> list;
class myClass(){
public myClass(){
list = new Dictionary<String, myClass>();
}
}
foreach (string name in array)
{
list.Add(name, new myClass())
}
回答by Willem T
You can use lists to store the objects so you can access them
您可以使用列表来存储对象,以便您可以访问它们
list<myClass> myClasses = new List<myClass>();
foreach (myClass object in myClasses)
{
//preform interaction with your classes here
}
回答by Michael Buen
Not applicable to C#, or any statically-typed language for that matter.
不适用于 C# 或任何与此相关的静态类型语言。
For curiosity, I tried if what I remembered in PHP(creating variables on-the-fly) is still correct.
出于好奇,我尝试了我在 PHP 中记住的内容(即时创建变量)是否仍然正确。
It's still the same PHP, last I used it was year 2000. You can generate variables on-the-fly, not saying it's advisable though, it pollutes the global variables, it can corrupt some existing variable or object with same name.
它仍然是相同的 PHP,我上次使用它是在 2000 年。您可以即时生成变量,但并不是说这是可取的,它会污染全局变量,它可能会破坏某些现有的变量或同名对象。
<?php
class MyClass
{
private $v;
function __construct($x) {
$this->v = $x;
}
public function getValue() {
return $this->v;
}
}
$one = new MyClass("I'm tough!");
echo "The one: " . $one->getValue() . "\n";
$i = 0;
foreach(array("one","two","three") as $h) {
$$h = new MyClass("Says who? " . ++$i);
}
echo "The one: " . $one->getValue() . "\n";
echo $two->getValue() . "\n";
echo $three->getValue() . "\n";
echo "loop\n";
foreach(array("three","one","two") as $h) {
echo $$h->getValue() . "\n";
}
?>
Outputs:
输出:
The one: I'm tough!
The one: Says who? 1
Says who? 2
Says who? 3
loop
Says who? 3
Says who? 1
Says who? 2
回答by aabiro
You can use this approach:
您可以使用这种方法:
var array = [srt1, srt2, str3];
var other_array = [];
for(var i = 0; i < array.length; i++){
other_array.push({
name: array[i]
})
}
And for lookup it is easy to find the instance you need by filtering:
对于查找,通过过滤很容易找到您需要的实例:
var instance1 = other_array.filter(function(result) {
return result.name == 'str1';
});

