Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 父母字典,添加孩子_C#_Dictionary - Fatal编程技术网

C# 父母字典,添加孩子

C# 父母字典,添加孩子,c#,dictionary,C#,Dictionary,嘿,伙计们,我需要包含多个子对象的数据库。我正在考虑制作一个字典,其中键是一个int,表示它是哪种类型的子对象,然后第二个字段是父对象。这样我就可以将任何子对象添加到字典中,但我似乎无法让它工作?有没有关于如何正确地做到这一点的想法 Dictionary<int, Parent> database; ChildOne newChildOne = new ChildOne(); ChildTwo newChildTwo = new ChildTwo(); database.Add(

嘿,伙计们,我需要包含多个子对象的数据库。我正在考虑制作一个字典,其中键是一个int,表示它是哪种类型的子对象,然后第二个字段是父对象。这样我就可以将任何子对象添加到字典中,但我似乎无法让它工作?有没有关于如何正确地做到这一点的想法

Dictionary<int, Parent> database;

ChildOne newChildOne = new ChildOne();
ChildTwo newChildTwo = new ChildTwo();

database.Add(1, newChildOne); 
database.Add(2, newChildTwo);
字典数据库;
ChildOne newChildOne=新ChildOne();
ChildTwo newChildTwo=新ChildTwo();
添加(1,newChildOne);
添加(2,newChildTwo);

您不需要字典来保存父子关系。 只需创建一个可以保存此关系的类:

public class MyEntity
{
    public MyEntity(int entityId, MyEntity parent)
    {
        this.Children = new List<MyEntity>();
        this.EntityId = entityId;
        this.Parent = parent;
        this.Parent.Children.Add(this);
    }

    public int EntityId { get; set; }

    public MyEntity Parent { get; set; }

    public List<MyEntity> Children { get; set; }
}
        MyEntity topParent = new MyEntity(1,null);
        MyEntity childOnLevel1 = new MyEntity(7,topParent);
        MyEntity childOnLevel2 = new MyEntity(4, childOnLevel1);

由于一个主要原因(字典中的键是唯一的),这不会像您描述的那样起作用。你需要描述你想要什么…做
ChildOne
ChildTwo
继承自
Parent
?你的错误是什么?什么不起作用?您是否遇到了错误,或者您是否不知道如何编写所需内容?