【问题标题】:How to add a instance of class into a variable c#?如何将类的实例添加到变量c#中?
【发布时间】:2022-06-27 21:16:08
【问题描述】:

如何将类的实例添加到变量c#中?

for (int i = 0; i < 8; i++)
{
    var msg = new Param
    {
       type = "text",
       text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
    };

    // What I need to do to acumulate msg variable into a new variable?
    
}

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    将对象附加到存在于循环外部的列表中,而不是仅附加到仅存在于循环内部的变量中。例如:

    var msgs = new List<Param>();
    for (int i = 0; i < 8; i++)
    {
        msgs.Add(new Param
        {
           type = "text",
           text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
        });
    }
    // here you have the list of Param objects created in your loop
    

    【讨论】:

      【解决方案2】:
      const int count = 8;
      var messages = new Param[count];
      for (int i = 0; i < count; i++)
      {
          var msg = new Param
          {
             type = "text",
             text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
          };        
          messages[i] = msg;
      }
      

      【讨论】:

        【解决方案3】:

        你可以创建一个参数列表

        var listParam = new List<Param>();
        for (int i = 0; i < 8; i++)
        {
            var msg = new Param
            {
               type = "text",
               text = $"{ message[i].VlrParam.Replace("\n", "").Replace("\r", "")}"
            };
        
            listParam.Add(msg);
            
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多