如何初始化对象数组中的对象列表 [英] How do I initialize a list of object in an array of object

查看:106
本文介绍了如何初始化对象数组中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这条代码让我失去了什么?当前我在内部for循环中有一个错误。错误是



类型'  System.NullReferenceException'在 testXMLSerializer.exe中发生 

其他信息: Object 引用 set object 的实例。







我的代码是这样的:



 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;

命名空间测试
{
class Class6
{
静态 void Main( string [] args)
{
作者[] author = new 作者[ 5 ];
int bookCount = 3 ;
for int i = 0 ; i < author.Length; i ++)
{
for int j = 0 ; j < bookCount; j ++)
{
author [i] .book [j] .Title = 书名;
author [i] .book [j] .Language = book language;
}
}

Console.Read();
}

}

public class 作者
{
public List< Book>预订{获取; set ;}
}

public class 预订
{
public string 标题{获取; set ;}
public string 语言{获取; 设置;}
}
}







基本上我想要的是拥有一个作者数组,每个作者都有一个Book of Book。谢谢



我的尝试:



代码编译但失败在执行期间。

解决方案

你的代码有点搞砸了。您创建了CAN HOLD 5作者对象的数组。您从未创建过这些Author对象。您必须先创建一个Author实例并将其分配给数组中的元素。

作者[] author = 作者[ 5 ]; 
for int i = 0 ...)
{
// 创建一个新作者并将其添加到数组。
作者newAuthor = 作者();
author [i] = newAuthor;

// 在新的Author对象中初始化图书集。
newAuthor.book = new 列表< book>();

// 创建新书列表并将其添加到作者
// 图书集。
for int j = 0 ...)
{
// 创建新书...
预订newBook = new Book();
newBook.Title = 书名;
newBook.Language = book language;

// 将其添加到当前作者的图书集中。
newAuthor.book.Add(newBook);
}
}





真的,这不是代表你的最有效方式数据。我把它作为一个例外,你试图了解这些东西是如何工作的。


在这一行之后:

作者[] author =  new 作者[ 5 ]; 



author 的所有元素都是 null 而不是的实际实例作者类。因此,进入第一个循环时要做的第一件事就是创建一个作者的实例并将其放入数组中。



另一个问题是,在创建作者实例时, book 成员也是。创建作者的实例时,必须为 book 属性赋值。您可以使用构造函数执行此操作:构造函数(C#编程指南) [ ^ ]



另一个问题是你试图访问 author [i] .book 的元素,但该元素在索引时尚不存在Ĵ。首先要添加它。

 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;

命名空间测试
{
class Class6
{
静态 void Main( string [] args)
{
作者[] author = new 作者[ 5 ];
int bookCount = 3 ;
for int i = 0 ; i < author.Length; i ++)
{
author [i] = 作者();
for int j = 0 ; j < bookCount; j ++)
{
author [i] .book.Add( new Book());
author [i] .book [j] .Title = 书名;
author [i] .book [j] .Language = book language;
// 或者,作为一个单行:author [i] .book.Add(new Book( ){Title =book title,Language =book language});
}
}

Console.Read();
}

}

public class 作者
{
public List< Book>预订{获取; set ;}

public 作者()
{
book = new List< Book>();
}

}

public class 预订
{
public string 标题{获得; set ;}
public string 语言{获取; 设置;}
}
}


我不喜欢在设置新项目时使用数组。框架具有内置的List< t>构造使这样做更容易。您也不必担心数组的明确大小。

 List< author> authors =  new  List< author>(); 
int authorCount = 5 ;
int bookCount = 3 ;
for int i = 0 ; i < authorCount; i ++)
{
var newAuthor = new 作者();
for int j = 0 ; j < bookCount; j ++)
{
newAuthor.book.Add( new 预订{
Title = 书名;
语言= book language;
});
}
authors.Add(newAuthor);
}



要将作者列表作为数组访问,只需要调用 authors.ToArray();


What I am missing for this piece of code for it to work? Current I have an error in the inner for loop. The error is

An unhandled exception of type 'System.NullReferenceException' occurred in testXMLSerializer.exe

Additional information: Object reference not set to an instance of an object.




The Code I have is like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Class6
    {
        static void Main (string[] args)
        {
            Author[] author = new Author[5];
            int bookCount = 3;
            for (int i = 0; i < author.Length; i++ )
            {
                for (int j = 0; j < bookCount; j++)
                {
                    author[i].book[j].Title = "book title";
                    author[i].book[j].Language = "book language";
                }
            }

                Console.Read();
        }

    }

    public class Author
    {
        public List<Book> book {get; set;} 
    }

    public class Book
    {
        public string Title {get; set;}
        public string Language {get;set;}
    }
}




Basically what I want is to have an array of Author and each author will have a List of Book. Thanks

What I have tried:

The code compile but failed during execution.

解决方案

You're code is a bit messed up. You created and array that CAN HOLD 5 Author objects. You never created these Author objects. You have to create an instance of Author and assign it to the element in the array first.

Author[] author = new Author[5];
for(int i = 0...)
{
    // Create a new Author and add it to the array.
    Author newAuthor = new Author();
    author[i] = newAuthor;

    // Initialize the book collection in the new Author object.
    newAuthor.book = new List<book>();

    // Create a list of new books and add them to the Author's
    // book collection.
    for(int j = 0...)
    {
        // Create a new book...
        Book newBook = new Book();
        newBook.Title = "book title";
        newBook.Language = "book language";

        // Add it to the book collection for the current Author.
        newAuthor.book.Add(newBook);
    }
}



Really, this isn't the most efficient way of representing your data. I'm taking this as an excersize that you're trying to learn how this stuff works.


After this line:

Author[] author = new Author[5];


all elements of author are null and not an actual instance of the Author class. So the first thing to do when entering the first loop, is creating an instance of Author and putting it in the array.

Another problem is that, when creating an Author instance, the book member is also null. When an instance of Author is created, you have to assign a value to the book property. You can do this using a constructor: Constructors (C# Programming Guide)[^]

Another problem is that you try to access an element of author[i].book, but that element does not exist yet at index j. You first have to add it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Test
{
    class Class6
    {
        static void Main (string[] args)
        {
            Author[] author = new Author[5];
            int bookCount = 3;
            for (int i = 0; i < author.Length; i++ )
            {
                author[i] = new Author();
                for (int j = 0; j < bookCount; j++)
                {
                    author[i].book.Add(new Book());
                    author[i].book[j].Title = "book title";
                    author[i].book[j].Language = "book language";
                    // or, as a one-liner: author[i].book.Add(new Book() { Title = "book title", Language = "book language" });
                }
            }
 
            Console.Read();
        }
 
    }
 
    public class Author
    {
        public List<Book> book {get; set;}

        public Author()
        {
            book = new List<Book>();
        }
    }
 
    public class Book
    {
        public string Title {get; set;}
        public string Language {get;set;}
    }
}


I don't like working with arrays when setting new items. The Framework has the built in List<t> construct which makes doing things like this much easier. You also don't have to worry about the explicit size of your array.

List<author> authors = new List<author>();
int authorCount = 5;
int bookCount = 3;
for(int i = 0; i < authorCount; i++)
{
    var newAuthor = new Author();
    for (int j = 0; j < bookCount; j++)
    {
        newAuthor.book.Add(new Book{
            Title = "book title";
            Language = "book language";
        });
    }
    authors.Add(newAuthor);
}


To access the authors list as an array all you need to call is authors.ToArray();


这篇关于如何初始化对象数组中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆