我有兩個對象MetaItems和Items。C#泛型和集合
MetaItem是對象的模板,而Items包含實際值。例如,「部門」被視爲元項目,「銷售」,「英國地區」,「亞洲地區」被視爲項目。
此外,我想維護這些元項目和項目上的親子關係。對於同一
我有下面的代碼 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfApplication12
{
public interface IEntity
{
int Id { get; set; }
string Name { get; set; }
}
public interface IHierachy<T>
{
IHierachy<T> Parent { get; }
List<IHierachy<T>> ChildItems { get; }
List<IHierachy<T>> LinkedItems { get; }
}
public class Entity : IHierachy<IEntity>, IEntity
{
#region IObject Members
private int _id;
public int Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
#endregion
#region IHierachy<IEntity> Members
public IHierachy<IEntity> _parent;
public IHierachy<IEntity> Parent
{
get
{
return _parent;
}
}
private List<IHierachy<IEntity>> _childItems;
public List<IHierachy<IEntity>> ChildItems
{
get
{
if (_childItems == null)
{
_childItems = new List<IHierachy<IEntity>>();
}
return _childItems;
}
}
private List<IHierachy<IEntity>> _linkedItems;
public List<IHierachy<IEntity>> LinkedItems
{
get
{
if (_linkedItems == null)
{
_linkedItems = new List<IHierachy<IEntity>>();
}
return _linkedItems;
}
}
#endregion
}
public class Item : Entity
{
}
public class MetaItem : Entity
{
}
}
以下是我的測試類 -
public class Test
{
public void Test1()
{
MetaItem meta1 = new MetaItem() { Id = 1, Name = "MetaItem1"};
MetaItem meta2 = new MetaItem() { Id = 1, Name = "MetaItem 1.1"};
Item meta3 = new Item() { Id = 101, Name = "Item 1" };
**meta1.ChildItems.Add(meta3);** // this line should not compile.
meta1.ChildItems.Add(meta2) // This is valid and gets compiled.
}
}
在測試類,當我buidling父子關係,我可以添加項目作爲元項目對象的子對象。在這裏我想編譯錯誤生成。
有人可以幫助我做到這一點。
-Regards 拉吉
如果元項目只是一個包含其他項目的項目,那麼它不是真的只是一個項目反正,其中'T = Item'? –
2010-06-23 13:52:45
與您的問題無關,但對於Entity.Id和Name,自動實施的屬性是您的朋友。 – dahlbyk 2010-06-23 13:58:15