Can I make the name of a new object variable in c#?

后端 未结 4 1476
一个人的身影
一个人的身影 2021-01-23 05:23

For example:

car Audi = new car();

Is it possible to something like this:

string name = Microsoft.VisualBasic.Interaction.Input         


        
相关标签:
4条回答
  • 2021-01-23 06:05

    The only way I can think of doing it is a C# version of

    car = Car() //basically Python way of initializing car
    
    del car
    
    car = Thing()
    
    0 讨论(0)
  • 2021-01-23 06:08

    No, you can't. In C# variables must be known at compile time, together with their names...

    What you can do is have a collection where to put all your cars... Like:

    var allmycars = new Dictionary<string, Car>();
    
    string name = Microsoft.VisualBasic.Interaction.InputBox("Name of new car?", "Add car");
    
    car mycar = new car();
    allmycars.Add(name, mycar);
    

    then you can:

    foreach (KeyValuePair<string, car> onecar in allmycars)
    {
        string name2 = onecar.Key;
        car car2 = onecar.Value;
    
        Console.WriteLine(name2);
    }
    
    0 讨论(0)
  • 2021-01-23 06:12

    No you cannot do that. But you can use a different data structure for something similar.

    Use Dictionary

    Dictionary<string, car> dictionary = new Dictionary<string,car>();
    if(!dictionary.ContainsKey(name))
    {
         dictionary.Add(name, new car());
    }
    
    0 讨论(0)
  • 2021-01-23 06:12

    This isn't possible as variable names are converted to addresses in memory whenever you compile the program.

    Since you're trying to name the variable after you compiled the program during runtime, it wouldn't make a difference since it's no longer a human readable name.

    0 讨论(0)
提交回复
热议问题