gpt4 book ai didi

C# 泛型和集合

转载 作者:太空狗 更新时间:2023-10-29 23:35:05 24 4
gpt4 key购买 nike

我有两个对象 MetaItems 和 Items。

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.
}
}

在测试类中,当我建立父子关系时,我可以将项目添加为元项目对象的子对象。这里我想要生成编译错误。

谁能帮我实现这个。

-问候拉吉

最佳答案

代码正在编译,因为 ChildItems将是 IList<Entity> , 其中包括 ItemMetaItem .如果你要制作Entity通用:

public class Entity<T> : IHierachy<T>, IEntity where T : IEntity { ... }

然后你会定义ItemMetaItem像这样:

public class Item : Entity<Item> { }

public class MetaItem : Entity<MetaItem> { }

在这种情况下,他们的 ChildItems将是正确的、更受限制的类型。

关于C# 泛型和集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3102190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com