更新时间:2023-12-02 23:14:34
正如我在评论中提到的,您遇到的主要问题是您的成员变量是静态的,因此当您设置该值时,它们在所有实例中都会更改.你应该这样改变你的代码:
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; }
}
以这种方式填写您的列表,不要忘记添加using System.Linq;
:
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;
注意:
静态
,它在该类的所有实例之间共享.property
获取或设置值,你不需要setX
或setY
,当你获取一个属性的值时,get
代码该属性的一部分将执行,当您为属性赋值时,它的 set
部分将执行.你可以这样定义属性:static
, it is shared between all instances of that calss.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:属性:
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
或更简单:
public int Id { get; set; }