Create dynamic variable name

前端 未结 5 1499
太阳男子
太阳男子 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条回答
  •  -上瘾入骨i
    2020-11-22 08:14

    try this one, user json to serialize and deserialize:

     using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Web.Script.Serialization;
    
        namespace ConsoleApplication1
        {
           public class Program
           {
              static void Main(string[] args)
              {
                  object newobj = new object();
    
                  for (int i = 0; i < 10; i++)
                  {
                    List temp = new List();
    
                    temp.Add(i);
                    temp.Add(i + 1);
    
                     newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
                  }
    
             }
    
         }
    
          public static class DynamicExtention
          {
              public static object AddNewField(this object obj, string key, object value)
              {
                  JavaScriptSerializer js = new JavaScriptSerializer();
    
                  string data = js.Serialize(obj);
    
                  string newPrametr = "\"" + key + "\":" + js.Serialize(value);
    
                  if (data.Length == 2)
                 {
                     data = data.Insert(1, newPrametr);
                  }
                else
                  {
                      data = data.Insert(data.Length-1, ","+newPrametr);
                  }
    
                  return js.DeserializeObject(data);
              }
          }
       }
    

提交回复
热议问题