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

后端 未结 4 1477
一个人的身影
一个人的身影 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: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 name = Microsoft.VisualBasic.Interaction.InputBox("Name of new car?", "Add car");
    
    car mycar = new car();
    allmycars.Add(name, mycar);
    

    then you can:

    foreach (KeyValuePair onecar in allmycars)
    {
        string name2 = onecar.Key;
        car car2 = onecar.Value;
    
        Console.WriteLine(name2);
    }
    

提交回复
热议问题