在循环中动态创建对象

时间:2012-06-07 11:15:28

标签: c# string object dynamic

我有一个循环的字符串数组。我想循环遍历数组,并在每次迭代时,创建一个名称与字符串值匹配的新对象。

例如;

string[] array = new string[] { "one", "two", "three" };

class myClass(){

    public myClass(){
    }
}

foreach (string name in array)
{
   myClass *value of name here* = new myClass(); 
}

将导致实例化三个对象,名称为“one”,“two”和“three”。

这可能还是有更好的解决方案?

9 个答案:

答案 0 :(得分:11)

你打算用静态类型语言做什么是不可能的。 IIRC,这在PHP上是可行的,但不建议这样做。

改为使用词典: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);
    }
}

输出:

hahah one!
hahah two!
hahah three!
Test
hahah two!

答案 1 :(得分:5)

虽然其他人已经给你一个候补,但没有人告诉他们为什么建议你。

那是因为您无法使用动态名称访问对象。

思考的食物:想一想,如果你能这样做,你会在它们被编码/命名之前如何访问它们。)

而是像其他人提到的那样创建Dictionary<string, myClass>

答案 2 :(得分:4)

改为使用Dictionary<String, myClass>

var dict= new Dictionary<String, myClass>();

foreach (string name in array)
{
    dict.Add(name, new myClass());
}

现在,您可以按名称访问myClass个实例:

var one = dict["one"];

或循环:

foreach (string name in array)
{
    myClass m = dict[ name ];
}

答案 3 :(得分:1)

您可以使用这种方法:

  var array = [srt1, srt2, str3];
  var other_array = [];

  for(var i = 0; i <  array.length; i++){
    other_array.push({
    name: array[i]
    })
  }

对于查找,可以很容易地通过过滤找到所需的实例:

var instance1 = other_array.filter(function(result) {
return result.name == 'str1';
});

答案 4 :(得分:0)

看起来您需要一个对象字典列表:

var myClassDictionary = new Dictionary<string,myClass>();

foreach (string name in array)
{
  myClassDicationry.Add(name, new myClass());
}

// usage:
// myClass["one"] <- an instance of myClass

我所知道的编程语言不允许您在运行时定义变量名称。

答案 5 :(得分:0)

你可以这样做 -

Dictionary<string, myClass> classes = new Dictionary<string, myClass>();

foreach(string name in array)
{
    classes[name] = new myClass();
}

然后您可以稍后参考命名实例

classes[name].MyClassMethod();

答案 6 :(得分:0)

您可以使用以下代码。

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())
 }

答案 7 :(得分:0)

您可以使用列表存储对象,以便访问它们

list<myClass> myClasses = new List<myClass>();
foreach (myClass object in myClasses)
{
    //preform interaction with your classes here 
}

答案 8 :(得分:0)

不适用于C#或任何静态类型的语言。

为了好奇,我试过,如果我在PHP中记住的(在运行中创建变量)仍然是正确的。

它仍然是相同的PHP,最后我用它是2000年。你可以动态生成变量,但不是说它是可取的,它会污染全局变量,它可以破坏一些现有变量或具有相同名称的对象

http://ideone.com/Xkpo1

<?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";

?>

输出:

The one: I'm tough!
The one: Says who? 1
Says who? 2
Says who? 3
相关问题