C#类对象覆盖

use*_*968 2 c# visual-studio-2010 winforms

我是OOP的新手,所以请考虑到这一点.我把从这个匹配中得到的数据放到一个类的对象中,但它是在foreach循环中完成的,所以每次调用它时,我的对象中的数据都会被覆盖,最后我想把所有数据放在我的宾语.但我只是从上一场比赛开始.我该怎么做才能避免这种覆盖?也许我是以完全错误的方式做到的?

foreach (var match in matches)
            {
                dataTable.Rows.Add(new Group[] { match.Groups["C0"], match.Groups["C1"], match.Groups["C2"], match.Groups["C3"], match.Groups["C4"] });

                MyClass sk = new MyClass();

                sk.Category = match.Groups["C0"].ToString();
                sk.Device = match.Groups["C1"].ToString();
                sk.Data_Type = match.Groups["C2"].ToString();
                sk.Value = match.Groups["C3"].ToString();
                sk.Status = match.Groups["C4"].ToString();
            }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

创建一个列表:

var list = new List<MyClass>();
foreach (var match in matches)
{
    dataTable.Rows.Add(new Group[] { match.Groups["C0"], match.Groups["C1"],
        match.Groups["C2"], match.Groups["C3"], match.Groups["C4"] });

    var sk = new MyClass {
        Category = match.Groups["C0"].ToString(),
        Device = match.Groups["C1"].ToString(),
        Data_Type = match.Groups["C2"].ToString(),
        Value = match.Groups["C3"].ToString(),
        Status = match.Groups["C4"].ToString()
    };
    list.Add(sk);
}
Run Code Online (Sandbox Code Playgroud)

然后你有列表中的所有项目.你也可以使用LINQ,例如:

var items = from match in matches
            select new MyClass {
                Category = match.Groups["C0"].ToString(),
                Device = match.Groups["C1"].ToString(),
                Data_Type = match.Groups["C2"].ToString(),
                Value = match.Groups["C3"].ToString(),
                Status = match.Groups["C4"].ToString()
            };
Run Code Online (Sandbox Code Playgroud)

并迭代items.