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

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

问题描述

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



例如;

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

class myClass(){

public myClass(){
}
}

foreach(数组中的字符串名称)
{
myClass *此处的名称* = new myClass();
}

将导致三个对象被实例化,名称为一,两个和三个。



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

解决方案

你想做什么是不可能用静态类型的语言。 IIRC可以在PHP上使用,但不太可取。



使用字典代替: http://ideone.com/vChWD

  using System; 
使用System.Collections.Generic;

class myClass {

public string Name {get;组; }
public myClass(){
}
}

class MainClass
{

public static void Main()
{
string [] array = new string [] {one,two,three};
IDictionary< string,myClass> col = new Dictionary< string,myClass>();
foreach(数组中的字符串名称)
{
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);
}
}

输出:

  haha​​h one! 
哈哈两个!
哈哈三!
测试
哈哈两个!


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?

解决方案

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.

Use dictionary instead: 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天全站免登陆