简体   繁体   中英

Using a variable for a class instance name C#

I've found a few threads on this for other languages but nothing for C#...

Basically, what I need is to instantiate a class with a different name each time (in order to be able to create links between the classes)

My current code:

foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
}

This creates a new NodeViewModel for every row in the table. What I really need is for each NodeViewModel to have a different name, but I have no idea how to do this.

I tried using a simple int in the loop but I can't add a variable into the class instance name. The (obviously wrong) code is here:

int i = 0;
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node+i = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    i++;
}

I figured by this point that I should be doing things differently and this was probably a terrible idea, but I'd like some advice! If it is possible I'd like to know - otherwise, some alternatives would be very helpful =)

Thanks!

I think you're looking for a collection. You can use a List<NodeViewModel> .

var nodelist = new List<NodeViewModel>();
foreach (DataRow dataRow in RoutingObjects.Rows)
{
    NodeViewModel node = CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString());
    nodelist.Add(node);
}

Now you can access every node in the list via index, for example:

NodeViewModel nvm = nodelist[0];

Tim Schmelter right. And, of course, wou can use Linq for more elegant code:

var nodelist = RoutingObjects.Rows.Select(dataRow=>CreateNode(dataRow.ItemArray[1].ToString(), new Point(globalx, globaly), false, dataRow.ItemArray[0].ToString())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM