【问题标题】:C#,what is the simplest way to add a class in List of class [closed]C#,在类列表中添加类的最简单方法是什么[关闭]
【发布时间】:2015-01-27 10:18:45
【问题描述】:

我多次记录一个类。我创建列表并创建 Stats 的对象,然后添加到我的列表中,但最近的记录被所有人复制。这是我的代码

List<Account> account = accountDao.All().Where(a => a.Role ==
Role.Distributor && a.ParentAccount.Id==1&&a.Active).ToList();
ViewBag.Accounts = account;
List<Stats> statsforRegions = new List<Stats>();
foreach (Account dist in account)
{
    List<int> userIdss = new List<int>();
    List<int> accountIdss = new List<int>();
    Stats stt = new Stats();
    stt=stats;
    getUserIdsRecursive(dist, userIdss, accountIdss);
    stt = calculate(stt, userIdss, accountIdss);
    statsforRegions.Add(stt);

}
ViewBag.StatsForRegions = statsforRegions;

【问题讨论】:

  • 请编辑您的标签,因为这是 C#,而不是 C。
  • 我不明白你的问题和问题?比如“但最近的记录被所有人复制。”
  • calculate 长什么样子?
  • 他是说最后创建的项目填满了整个列表(因为没有创建新项目。-见 GazTheDestoyer 的回答

标签: c# list class


【解决方案1】:

您正在创建一个新的Stats 对象并将其分配给stt

Stats stt = new Stats();

然后您将另一个对象 (stats) 分配给 stt,这意味着原始对象被丢弃。

stt = stats.

您的代码没有显示 stats 是什么,但我认为它是您所指的“最近记录”。

【讨论】:

  • 在分配 stt=stats 后 stt 记录不同但是当我在 statsforRegions.Add(stt);它替换列表中的所有其他记录
  • 那么我只能假设您每次都从 calculate() 返回相同的对象。
  • No no 计算方法后我有我需要的记录。
【解决方案2】:

这是一个将对象添加到列表的基本示例

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<MyObject> MyList = new List<MyObject>();

        for (int x = 1; x <= 10; x++)
        {
            MyObject obj = new MyObject();
            obj.Id = x;

            MyList.Add(obj);                       
        }

        //now show the list

        foreach(MyObject obj in MyList)
        {
            Console.WriteLine(obj.Id.ToString());
        }
    }
}

public class MyObject
{
    public int Id {get;set;}    
}

我也为你写了一个小提琴https://dotnetfiddle.net/cnNiI5

【讨论】:

    【解决方案3】:

    我认为您的 calculate 函数返回相同的值并且

    stats
    

    没有改变。

        stt=stats;
        getUserIdsRecursive(dist, userIdss, accountIdss);
        stt = calculate(stt, userIdss, accountIdss);
    

    【讨论】:

    • 是的,在计算 stt 有我需要的记录之后。但是当我将此对象添加到列表时,它的记录被列表中的所有其他记录复制
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2017-09-03
    相关资源
    最近更新 更多