简体   繁体   English

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

[英]How to add a instance of class into a variable c#?

How to add a instance of class into a variable c#?如何将类的实例添加到变量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?
    
}

Append the object to a list that exists outside of the loop, instead of just to a variable that only exists inside the loop.将对象附加到存在于循环外部的列表中,而不仅仅是附加到仅存在于循环内部的变量中。 For example:例如:

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

You can create a list of Param您可以创建一个参数列表

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);
    
}
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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM