每次创建新产品时,我都需要一个唯一的ID。
我的代码创建了相同的Guid(00000000-0000-0000-0000-000000000000)每个项目我将它添加到列表中,并且它不是唯一的。
请告诉我,如果我在这段代码中做错了。这是我的代码。
class Product
{
private Guid _ID ;
private String _Name = string.Empty;
private String _Price = string.Empty;
public Guid ID
{
get { return _ID; }
set { _ID = value; }
}
public string Name
{
get { return (_Name); }
set { _Name = value; }
}
public string Price
{
get { return (_Price); }
set { _Price = value; }
}
public Product(Guid ID, string Name, string Price)
{
_ID = ID;
_Name = Name;
_Price = Price;
}
public Product()
{
// TODO: Complete member initialization
}
public static void Main()
{
List<Product> productList = new List<Product>();
productList.Add(new Product() { Name = "shoe", Price = "80"});
productList.Add(new Product() { Name = "Hand Bag", Price = "180" });
productList.Add(new Product() { Name = "Pen", Price = "8" });
var cheapestItem = (from i in productList orderby i.Price descending select i.Name).Take(1);
Console.WriteLine(cheapestItem);
Console.ReadLine();
}
答案 0 :(得分:14)
您需要每次都致电Guid.NewGuid()
创建一个新的唯一GUID。
Guid
的默认值为Guid.Empty
,这是您所看到的(全部0&#39;)。
答案 1 :(得分:2)
您没有将Guid传递给类构造函数或通过对象初始化程序。
执行:
productList.Add(new Product() { ID = Guid.NewGuid(), Name = "shoe", Price = "80"});
在类中为字段分配默认值,00000000-0000-0000-0000-000000000000
是Guid的默认值。
因为你有一个类构造函数,它包含三个参数 Guid,您可以使用它:
productList.Add(new Product(Guid.NewGuid, "shoe", "80"));
答案 2 :(得分:2)
您甚至没有生成Guid
,因此每次都会获得默认值。使用Guid.NewGuid()
方法生成Guid
。