2017-08-29 55 views
5

几天后,我面临一个测试,我被要求回答以下问题:虽然它似乎基本,但我有一些疑问和我自己的意见列表VS阵列:一对多和有一个关系

一个出版中心出版书籍。一个作家可以写很多书,一本书有一个作者

有四个选项,其中,我省略了两个不接近的选项。因此,留下了两个选项,如下所示:

一种选择,带有表

public class Publisher 
{ 
    public int PublisherId { get; set;} 
    public string PublisherName { get; set;} 
    public string Address { get; set;} 
    public List<Author> Authors { get; set;} 
    public List<Book> Books{ get; set;} 
} 

public class Author 
{ 
    public int AuthorId { get; set;} 
    public string AuthorName { get; set;} 
    public string AuthorAddress { get; set;} 
    public List<Book> Books{ get; set;} 
} 

public class Book 
{ 
    public int BookId { get; set;} 
    public string BookName { get; set;} 
    public Author Author { get; set;} 
} 

另一种选择使用Array

public class Publisher 
{ 
    public int PublisherId { get; set;} 
    public string PublisherName { get; set;} 
    public string Address { get; set;} 
    public Author[] Authors { get; set;} 
    public Book[] Books{ get; set;} 
} 

public class Author 
{ 
    public int AuthorId { get; set;} 
    public string AuthorName { get; set;} 
    public string AuthorAddress { get; set;} 
    public Book[] Books{ get; set;} 
} 

public class Book 
{ 
    public int BookId { get; set;} 
    public string BookName { get; set;} 
    public Author Author { get; set;} 
} 

在同一时间,我看着这个链接了解差异:List Vs Array

那么,首先,我选择了第一个选项(我的回答wa s),并相信,List有更多的功能,将是一个更好的选择。另一个原因是,我在项目中使用EF当与表的关系专门为一个一对多,创造了那么类的工作,有List这样一个集合:

public List<Book> Books{ get; set;} 

其次,我是思考,如果数组可以用于相同的,但我所学的数组数据结构对于固定数据是完美的。我希望,我正走在正确的轨道上。

最后我无法理解从链路两点提供

1)作为计数器 - List<T>是一维的;因为你有像int [,]或string [,,]这样的矩形(等)数组,但在对象模型中还有其他建模方法(如果需要的话)

我的观点 - 一维意思是List一维数组或相关的东西。

2)有点困惑我的意思是在什么情况下我们应该使用Array以下内容?虽然它解释,但需要一些更多的澄清:

  • 它做了很多位移的,所以一个byte []是非常重要的 进行编码;

  • 我使用本地滚动字节[]缓冲区,我发送到底层流(和v.v.)之前填充;比BufferedStream 等快;

  • 它内部使用基于数组的对象模型(Foo []而不是List),因为大小一旦构建就被修复,并且需要非常快速地变为 。
+0

嗯,*个人意见*:除了数组/集合 - 问题我认为如果逐字逐个要求分开,两个soltuions都是不正确的:有两个演员提到:“Writer”和“Author”。这两者可能不一样。在发布环境中,我认为,了解“幽灵作家”并不是太牵强。但如果这些仍然是唯一合理的选择,那么我认为我可能会采取的太过分了。 – Fildor

+0

我想,**作者**和**作家**是同一个词。这似乎令人困惑或混淆。 –

+0

考虑一本书可以有多个作者(或作者),是以正确的方式构建的基本关系逻辑?从我认为一对多关系通常有'List'作为其他表的参考。 –

回答

1

正如链接所说,首先你必须明白,默认情况下数组具有指定内存如何分配的特定大小。如果你超过这个分配,你将不得不再次分配内存给整个阵列。

列表是动态的,基本上意味着一个元素只会保持指向下一个元素的指针,所以很容易在任何地方(前,后,中)添加新项。主变量只保留指向第一个元素的指针,这样就可以将列表放在一起。

说实话,在你的例子中,我会使用列表版本,只是因为它们可以根据需要扩展和收缩,而且它的内存效率更高。

在附注上,我宁愿使用IList或IEnumerable类型,以便在创建者生成新对象时可以打开具体的实现。

当您需要像添加,删除等操作时,您将使用IList,并且当您只需枚举元素(即搜索,筛选)时使用IEnumerable。

要回答你的问题: 1)数组是多维的,像int [,]这可以很容易地用IList>;这是全部抽象的,我建议你研究链表类型(https://www.tutorialspoint.com/data_structures_algorithms/linked_list_algorithms.htm),也许这将回答几个问题 2)这是非常特定于该应用程序,通常一些字节数组操作将默认返回字节数组,因为尺寸是可以预测的,所以不确定你真正想要什么。

希望这会有所帮助。

+0

我同意这一点,并感谢解释。我期待你最后回答下两个问题。 – user8512043

+0

我已经编辑了答案,希望能为你解决一些问题 –

+1

其实,['List '](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs, 2765070d40f47b98,references)在内部使用一个数组,它不是一个链表。 –

相关问题