在List中添加字符串并获取它C#

时间:2022-01-28 22:55:35

I want to store string to list every time i Click a button. So far I did,

我希望每次单击按钮时都将字符串存储到列表中。到目前为止我做到了,

List<string> data = new List<string>();
private void Button_Click(object sender, MouseButtonEventArgs e)
{
   data.Add("Some string value");
}

I want 3 string value if I click button 3 time in a list.

如果我在列表中单击按钮3次,我想要3个字符串值。

1 个解决方案

#1


1  

Try using static keyword , working code

尝试使用静态关键字,工作代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static List<string> data = new List<string>();
        public static void Main(string[] args)
        {
            //Your code goes here
           new Program().addelements();
           new Program().addelements();

           for(int i=0; i<data.Count;i++)
            Console.WriteLine(data[i]);
        }

        private  void addelements()
        {
           data.Add("Some string value");
        }
    }
}

#1


1  

Try using static keyword , working code

尝试使用静态关键字,工作代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static List<string> data = new List<string>();
        public static void Main(string[] args)
        {
            //Your code goes here
           new Program().addelements();
           new Program().addelements();

           for(int i=0; i<data.Count;i++)
            Console.WriteLine(data[i]);
        }

        private  void addelements()
        {
           data.Add("Some string value");
        }
    }
}