C# 包含列表的复合类
我希望有一个类,包含关于我在软件中表示的名词的所有其他细节C# 包含列表的复合类,c#,list,collections,C#,List,Collections,我希望有一个类,包含关于我在软件中表示的名词的所有其他细节 public class Customer { public int Id { get; set; } public string Name { get; set; } public List<Note> Notes { get; set; } } public class Note { public string Notes { get; set; } public DateTime DateAdd
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Note> Notes { get; set; }
}
public class Note
{
public string Notes { get; set; }
public DateTime DateAdded { get; set; }
}
我在入口点或按钮单击中使用SqlCommand从两个不同的存储过程中获取数据-没关系,下面是一个示例
static List<Note> notes = new List<Note>();
static string conString = "Server=localhost;Database=MyDb;Trusted_Connection=True;";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand("sp_GetCustomerNotes", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
cmd.Parameters["@CustomerId"].Value = 1;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Note note = new Note(
(string)reader["Notes"].ToString(),
DateTime.Parse(reader["DateAdded"].ToString())
);
notes.Add(note);
}
这些都是很标准的东西
这是我的问题。一旦我获得了我的客户对象的数据,我想将这个客户的注释对象中的所有注释都包含在一个类/对象中:Customer。那我该怎么做呢
为Customer表执行相同的代码,我尝试使用foreach循环,但没有效果
while (reader.Read())
{
// removed because this is the same code as above with a diff sproc
Customer customer = new Customer();
customer.Name = (string)reader["Name"];
}
foreach (Note note in notes)
customer.Notes = note;
// ERROR HERE -->
Error 4 Cannot implicitly convert type 'Note' to 'System.Collections.Generic.List<Note>'
所以我有点不清楚怎么做
请提供帮助。如果要将注释添加到注释中,如果它是列表的集合,可以通过以下方式添加:
customer.Notes.Add(note);
所以我发现,即使Customer对象已经实例化,Notes类(Customer类的成员)也需要创建,所以我创建了一个方法调用来获取Notes集合 首先,我创建了一个函数来获取注释
static List<Note> GetCustomerNotes()
{
Customer c = new Customer();
c.Notes = new List<Note>();
foreach (Note note in notes)
c.Notes.Add(note);
return c.Notes;
}
那么customer.Notes=Notes呢?那有什么问题?您需要深度拷贝还是什么?customer.Notes=Notes或customer.Notes.Addnote
while (reader.Read())
{
Customer customer = new Customer(
(string)reader["Name"],
GetCustomerNotes()
);
}