Variables con nombres de variables en C# [duplicado]

In php you can create variables with variable names using ${'variable'.$count}

but at the moment I need this in C#, is there a C# equivalent for this?

EDIT:

Basically what im trying to do is create a timer every time the space bar is pressed, the first time the name is timer1 second time timer2..

preguntado el 28 de mayo de 14 a las 12:05

After your Edit: I would still go for a Dicitonary because that's the way to keep track of values by keys. (Dictionary also ensures there are no duplicate keys). However I Would change the type for the value from object to Timer -

2 Respuestas

You could store the values in a Dictionary in C#. That way you could retrieve a value according to a specific key.

IDictionary<string, object> variables = new Dictionary<string, object>();

Add a variable:

variables.Add("varname", 11);

Then to retrieve te variables you can use:

var myVar = variables.SingleOrDefault(x => x.Key == "varname");

Note to include using System.Linq; que se utilizará .SingleOrDefault()

Debido a que el object type is used as a value, all kinds of variables can be stored; (int, string, custom class instances). but note that you'll have to cast the variable back to your type when using it

EDIT: If you only use Timers, use this dictionary declaration:

IDictionary<string, Timer> variables = new Dicitonary<string, Timer>();

contestado el 28 de mayo de 14 a las 13:05

Using Dictionary is a good way! +1 - Raúl Tripathi

Thank you for your help. Can I use a variable instead of 11? - Wim

@Wim 11 is an int variable. You can use any variable you want. Also a Timer as your edit reveils. But if the collection will only contain timers, i suggest changing the object Type of the dictionary to Timer. In that way you won't need to cast the value back after retrieving it - middelpat

Then create your own Timer type, where you encapsulate the logic of updating the name. No need for variable variables.

class MyTimer
{
 // ...

 public void Increment()
 {
   this.name = "name" + (count++).ToString();
 }

 private string name;
 private int cout;
}

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.