Create dynamic variable name

前端 未结 5 1593
太阳男子
太阳男子 2020-11-22 07:56

Can we create dynamic variable in C#?

I know my below code is threw error and very poor coding. But this code have small logic like create dynamic variable

5条回答
  •  时光取名叫无心
    2020-11-22 08:29

    C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace QuickTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary names = new Dictionary();
    
    
                for (int i = 0; i < 10; i++)
                {
                    names.Add(String.Format("name{0}", i.ToString()), i);
                }
    
                var xx1 = names["name1"];
                var xx2 = names["name2"];
                var xx3 = names["name3"];
            }
        }
    }
    

提交回复
热议问题