在我的应用程序中,我有一个具有枚举属性的对象列表。为了让这个类稍微更友好一点,我决定添加一个列表,根据它们的enum属性返回这些对象的特定主题。列表属性返回其他列表属性的子集,但可以更改
我遇到的问题是,如果我添加对象到这个子集,它不会更新主列表。
这可能吗?
public class foo
{
public int Id { get; set; }
public string Description { get; set; }
public List<bar> bars { get; set; }
//list of only bars of barType one
public List<bar_one> bar_ones
{
get
{
return (this.bars.Where(x => x.barType == barType.one)).ToList().Cast<bar_one>().ToList();
}
}
public foo()
{
this.bars = new List<bar>();
}
}
public class bar
{
public bar() { }
public bar(barType bt) {
this.barType = bt;
}
public int Id { get; set; }
public string Description { get; set; }
public barType barType { get; set; }
}
public class bar_one : bar
{
public bar_one() : base(barType.one) { }
}
public enum barType
{
one,
two,
three
}
public static void Main()
{
foo f = new foo();
f.bars.Add(new bar { Id = 1, Description = "b1", barType = barType.one });
f.bars.Add(new bar { Id = 2, Description = "b2", barType = barType.two });
//this does not break, but the amount of objects in f.bars remain the same.
f.bar_ones.Add(new bar_one { Id= 3, Description="b1_2" });
}
你真的需要能够酒吧添加到'bar_ones'?为什么不把它们添加到'bars'属性呢? –
如果你真的想要这种行为,我认为你需要创建一个自定义的集合类型来包装你的酒吧列表,并从中过滤出一个特定的酒吧类型,并且还将一个添加方法委托给你的内部列表。 –
@AndreasZita,我可以(这是以前的设计的一部分),但我认为这种方式更漂亮,更方便用户。 –