循环创建和添加新对象到ArrayList的 [英] Looping to Create and Add New Objects to ArrayList

查看:364
本文介绍了循环创建和添加新对象到ArrayList的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑为您节省从通过这个整个后读
tldr:,除非你想那个对象的所有实例都具有相同的值该字段对象的字段不应该是静态

我试图创建和填充博客对象的ArrayList。我知道一般的方式做到这一点:

 创建的博客的ArrayList
环(某些情况)
     创造新的博客
     此博客添加到AL

然而,当我试图将而(datareader.read())循环内做到这一点,所有的ArrayList中的元素是完全一样的博客。具体来说,我结束了装满多个指针从数据库表中的最后的博客对象的ArrayList。这里是我的code:

 公共静态的ArrayList AllBlogs()
    {
        SqlDataReader的博士= anonPage.ExecuteReader(SELECT * FROM Kristina_Blogs);        ArrayList的allBlogs =新的ArrayList();        如果(dr.HasRows)
        {
            而(dr.Read())
            {
                博客B =新的博客();                //抓住从Kristina_Blogs一行,并分配这些属性为b
                b.setTitle(DR [标题]的ToString());
                b.setMessage(DR [消息]的ToString());
                b.setId(DR [ID]);                allBlogs.Add(二);
            }
        }
        dr.Close();
        返回allBlogs;
    }

正如我以前说过,这样的结果是一个充满指针从Kristina_Blogs表的最后博客的ArrayList。我想象的ArrayList allBlogs看起来像[B,B,B,... B],因此,他们都得到更新,当我说b.setTitle()等,但怎么能这样的话,如果我创建一个新的博客对象在每次迭代的开始?


下面是一些额外的信息,你就不用看了,但它可能澄清有关问题的结构有些混乱:


  1. 博客对象ID,标题和消息字段和他们各自的getter / setter方法​​

  2. Kristina_Blogs是一个表,再presenting这些博客与ID,标题,信息栏

  3. 的建议说,包括我的数据库引擎的标记,但我找不到它的标记:微软SQL Server Management Studio中

  4. 这code完美的作品,当我用字符串,而不是博客的ArrayList

编辑:包括来自博客类code

 公共类博客
{
    公共应用对myApp;
    公共静态字符串称号;
    公共静态字符串消息;
    公共静态INT标识;    //构造
    公共博客(){}
    公共博客程序(App应用){this.myApp =应用; }    //所有的getter和setter方法​​如下
    公共字符串的getTitle(){返回标题; }
    公共无效的setTitle(串T){标题= T; }}


解决方案

您,正如我在评论中提到的主要问题是你的成员变量是静态的,所以当你设置的值,它们在所有情况下更改。你应该改变你的code是这样的:

 公共类博客
{
    公众诠释标识{搞定;组; }
    公共字符串名称{搞定;组; }
    公共字符串消息{搞定;组; }
}

,并填写您的名单这样,不要忘了添加使用System.Linq的;

  VAR的结果=新的List<博客>();
VAR连接= @连接字符串;
VAR命令=SELECT * FROM Kristina_Blogs
VAR适配器=新System.Data.SqlClient.SqlDataAdapter(命令连接);
VAR的dataTable =新的DataTable();//获取数据
adapter.Fill(dataTable的);dataTable.Rows.Cast<&的DataRow GT;()了ToList()。
            .ForEach(行=>
            {
                变种B =新的博客();
                b.Id = row.Field< INT>(ID);
                b.Title = row.Field<串GT(标题);
                b.Message = row.Field<串GT;(信息);                result.Add(二);
            });返回结果;

注意:


  • 当你创建一个成员 静态 ,这是CALSS的所有实例之间共享。

  • 在C#中,您可以使用 属性 ,以获取或设置值,你不需要 setX的 SETY ,当你得到一个属性的值,在 GET code该属性将执行,当你分配一个值属性的设置的一部分将被执行。你可以定义属性是这样的:

属性:

 私人诠释身份证;
公众诠释标识
{
    得到
    {
        返回ID;
    }
    组
    {
        ID =价值;
    }
}

或更简单:

 公众诠释标识{搞定;组; }

Edit to save you from reading through this whole post tldr: an object's fields should not be static unless you want all instances of that object to have the same value for that field

I'm trying to create and populate an ArrayList of Blog objects. I do know the generic way do this:

create ArrayList of Blogs
loop (some condition)
     create new Blog
     add this Blog to AL

However, when I attempt to do so within the while(datareader.read()) loop, all of the elements in the ArrayList are exactly the same Blog. Specifically, I end up with an ArrayList filled with multiple pointers to the very last Blog object from the database table. Here is my code:

 public static ArrayList AllBlogs()
    {
        SqlDataReader dr = anonPage.ExecuteReader("SELECT * FROM Kristina_Blogs");

        ArrayList allBlogs = new ArrayList();

        if (dr.HasRows)
        {
            while (dr.Read())
            {
                Blog b = new Blog();

                //grab a row from Kristina_Blogs and assign those attributes to b
                b.setTitle(dr["title"].ToString());
                b.setMessage(dr["message"].ToString());
                b.setId(dr["id"]);

                allBlogs.Add(b);
            }
        }
        dr.Close();
        return allBlogs;
    }

As I said before, the result of this is an ArrayList filled with pointers to the very last blog from the Kristina_Blogs table. I imagine the ArrayList allBlogs looks like [b, b, b, ... b] and therefore they ALL get updated when I say b.setTitle() etc. But how can this be the case if I am creating a NEW Blog object at the beginning of each iteration?


Here is some extra info that you don't have to read but it might clear up some confusion about the structure of the problem:

  1. Blog object has id, title, and message fields and their respective getter/setters
  2. Kristina_Blogs is a table representing these blogs with columns for id, title, message
  3. The suggestions say to include a tag for my DB engine but I can't find a tag for it: Microsoft SQL Server Management Studio
  4. This code works perfectly when I use an ArrayList of Strings instead of Blogs

Edit: Including the code from Blog class

public class Blog
{
    public App myApp;
    public static string Title;
    public static string Message;
    public static int Id;

    //constructors
    public Blog() { }
    public Blog(App App) { this.myApp = App; }

    //all getters and setters look like this
    public string getTitle() { return Title; }
    public void setTitle(string t) { Title = t; }

}

解决方案

The main problem you have, as I mentioned in comments is your member variables are static, so when you set the value, they change in all instances. you should change your code this way:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
}

And fill your list this way, don't forget to add using System.Linq;:

var result = new List<Blog>();
var connection = @"your connection string";
var command = "SELECT * FROM Kristina_Blogs";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();

//Get data
adapter.Fill(dataTable);

dataTable.Rows.Cast<DataRow>().ToList()
            .ForEach(row =>
            {
                var b = new Blog();
                b.Id = row.Field<int>("Id");
                b.Title = row.Field<string>("Title");
                b.Message = row.Field<string>("Message");

                result.Add(b);
            });

return result;

Note:

  • When you create a member static, it is shared between all instances of that calss.
  • In C# you can use property to get or set values, you don't need to setX or setY, when you get the value of a property, the get code of that property will execute and when you assign a value to a property the set part of it will execute. you can define properties this way:

Property:

private int id;
public int Id
{
    get
    {
        return id;
    }
    set
    {
        id = value;
    }
}

or more simple:

public int Id { get; set; }

这篇关于循环创建和添加新对象到ArrayList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆