我试图使用C#和VS 2008从SQL Server 2005中的 t_Food
表中选择 food_ItemName
和 food_UnitPrice
.
我有以下代码:
private SqlConnection connection;
private void GetDatabaseConnection()
{
string connectionString = @"Server = RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; Database = HotelCustomerManagementDatabase";
connection = new SqlConnection(connectionString);
connection.Open();
}
public Food PopulateFoodItemListview()
{
GetDatabaseConnection();
string selectFoodItemQuery = @"SELECT food_ItemName, food_UnitPrice FROM t_Food";
SqlCommand command = new SqlCommand(selectFoodItemQuery, connection);
SqlDataReader reader = command.ExecuteReader();
Food food = new Food();
List foodList = new List();
while (reader.Read())
{
food.ItemName.Add(reader.GetString(0));
MessageBox.Show("ItemName: "+ food.ItemName);
food.UnitPrice.Add(reader.GetDouble(1));
MessageBox.Show("UnitPrice: " + food.UnitPrice);
}
connection.Close();
return food;
}
在 Food
类中,我有以下代码:
public class Food
{
private List itemName = new List();
private List unitPrice = new List();
private double itemUnit;
private Customer foodCustomer = new Customer();
public List ItemName
{
get { return itemName; }
set { itemName = value ; }
}
public List UnitPrice
{
get { return unitPrice; }
set { unitPrice = value; }
}
public double ItemUnit
{
get { return itemUnit; }
set { itemUnit = value; }
}
public double GetItemPrice(double itemUnit, double unitPrice)
{
double itemPrice = itemUnit*unitPrice;
return itemPrice;
}
}
在messageBox中它应该显示Rice,Mutton,Beef以及它们的价格50,100,150 . 但它显示 ItemName: System.Collections.Generic.List
1[System.String]和
ItemName: System.Collections.Generic.List1[System.Double]
有什么问题?
5 回答
ItemName和UnitPrice是List对象,而不是单个项目 . 将对象传递给MessageBox函数时,它将调用对象上的ToString()以获取可显示的字符串 . List上的ToSting()返回您看到的字符串 . 您应该使用索引来获取列表中的项目:
要么
问题是food.Item名称返回
List<string>
并且您正在对List<string>::ToString
进行隐式调用,该调用返回该类型的详细信息 . 您应该将最后输入的项目请求为food.ItemName[food.ItemName.Count - 1]
,或者您可以遍历列表中的所有项目以输出所有名称/价格 .你应该指定:
这样,当您添加名称时,您可以执行以下操作:
你注意到的问题是food.itemName只是一个列表而不是一个字符串 . 因此,您可以通过以下列表从列表中获取字符串:
myList[someIndex],
这是您的List对象,后跟列表中项目的索引 .填写食品名称列表后,您应该可以预先知道:
Aside from this I am a bit concerned with the wording of this class. 如果Food对象代表一个食物实体,那么为什么itemName和price
list
这个类的成员呢?它们应该只是string
和double
类型的属性 . 创建食物对象时,对象包含名称和价格 .您可以这样做:
以及如何使用该类:
food.ItemName是List,而不是字符串,因此ToString()返回类型 . 你想要的是:
和UnitPrice相同:
您的
Food
类用于表示单个食物项,因此您的itemName
和unitPrice
成员应分别为string
和double
类型(不是List
,用于存储多个值) .然后,
PopulateFoodItemListview
应返回List<Food>
(不是Food
) . 在reader.Read()
循环中,您应该创建一个新的Food
实例,使用数据库中的相应值填充它,然后将其添加到List<Food>
集合(然后在方法结束时返回) .Update: 喜欢这个: