2011-11-18 75 views
0

我有以下类。我希望在所有Admin_Fee_Prop项目中保持BP值的唯一性。我不知道应该使用什么集合类型的属性Admin_Fee_Prop,或者如何定义Admin_Fee类,以便BP属性值在所有Admin_Fee_Prop项中保持唯一?有时候我可能还需要复合材料的独特性。保持类中属性/属性值的唯一性

Public Class BE 
{ 
    public string Name {get;set:) 
    public List<Admin_Fee> Admin_Fee_Prop {get;set:) 
} 

public class Admin_Fee 
    { 
     public string BP_Name { get; set; } 

     public int BP { get; set; } 

     public int BP_Perc { get; set; } 

} 

回答

1

定义BP财产Guid而不是int。调用Guid.NewGuid()来生成新的唯一值。

如果您想在每次创建Admin_Fee_Prop时对其进行实例化,请添加一个将为BP生成新值的默认构造函数。另外,您可以将Admin_Fee_Prop存储在密钥将为Admin_Fee_Prop.BP的字典中,并且值将是Admin_Fee_Prop类型的对象。

0

使用HashSet<Admin_Fee>,并实施Admin_FeeEqualsGetHashCode,这样的Admin_Fee两个实例被认为是相等的,如果有相同的BP值:

public Class BE 
{ 
    public string Name {get;set:) 
    public HashSet<Admin_Fee> Admin_Fee_Prop {get;set:) 
} 


public class Admin_Fee 
{ 
    public string BP_Name { get; set; } 
    public int BP { get; set; } 
    public int BP_Perc { get; set; } 

    public override bool Equals(object other) 
    { 
     if (!(other is Admin_Fee)) 
      return false; 
     return this.BP == ((Admin_Fee)other).BP; 
    } 

    public override int GetHashCode() 
    { 
     return BP; 
    } 

} 

另一种可能的方法是实施IEqualityComparer<Admin_Fee>,并通它作为HashSet<Admin_Fee>构造函数的参数。

有些时候,我可能还需要独特的复合材料性能

在你需要采取EqualsGetHashCode所有这些特性考虑在内的话。有关如何从多个属性生成哈希码的示例,请查看this answer