在循环中动态创建对象

use*_*453 11 c# string dynamic object

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

例如;

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

class myClass(){

    public myClass(){
    }
}

foreach (string name in array)
{
   myClass *value of name here* = new myClass(); 
}
Run Code Online (Sandbox Code Playgroud)

将导致三个对象被实例化,名称为"one","two"和"three".

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

Mic*_*uen 12

在静态类型的语言中,你打算做什么是不可能的.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

hahah one!
hahah two!
hahah three!
Test
hahah two!
Run Code Online (Sandbox Code Playgroud)


Nik*_*wal 5

虽然其他人已经给你一个候补,但没有人告诉他们为什么他们推荐你.

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

(深思熟虑:如果你能做到这一点,请考虑一下,在你编码/命名之前你将如何访问它们.)

而是创建一个Dictionary<string, myClass>像其他人提到的.