在循环动态创建对象 [英] Creating objects dynamically in loop

查看:118
本文介绍了在循环动态创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我通过循环的字符串数组。我想通过数组并在每个迭代循环,创建该字符串值相匹配的名称的新对象。

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.

例如;

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?

推荐答案

什么是你要做的是不可能在静态类型语言。 IIRC,这是可能的PHP,它虽然是不可取的。

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.

使用字典而不是: 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!

这篇关于在循环动态创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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