C# - 如何将 List 属性添加到类并添加属性值

时间:2021-07-18 22:44:36

标签: c# list class object oop

这些是我的指示:

  • 在 Book 类中创建一个名为 Distributors 的属性。此属性应为 Distributor 类型的列表。
  • 将您创建的 3 个分销商添加到您最初创建的 5 个图书类对象中的任何一个。

在将 distributors1 添加到 book 之后,我尝试通过以下方式检查这本书:

book.Distributors(distributor1);
Console.WriteLine(book); 

我在运行时没有出错,但我的 WriteLine 没有将我的书与添加的经销商一起吐出,所以我很确定我做错了。

将 Distributors 的 List 属性添加到我的 Book 类的正确方法是什么?此外,一旦我将 list 属性添加到我的 Book 类中,我将如何正确地将 distributor1 添加到 book

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp
{
    public class Book
    {
        public string Title { get; set; }

        public string Author { get; set; }

        public int Year { get; set; }

        public string CoverType { get; set; }

        public List<Distributor> Distributors(Distributor distributor)
        {
        List<Distributor> newList = new List<Distributor>();
        newList.Add(distributor);
        return newList;
        }

        public Book(string title, string author, int year, string coverType)
        {
            this.Title = title;
            this.Author = author;
            this.Year = year;
            this.CoverType = coverType;
        }
        
    }
}


using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            
            var book = new Book("Art of War", "Sun Tzu", 1999, "Hard");

            var location1 = new Location("123 Sesame St", "Fake City", "CA", "92604");
            var distributor1 = new Distributor("Big Bird", location1);
           
            book.Distributors.Add(distributor1);  

            Console.ReadLine();

        }

    }
}

1 个答案:

答案 0 :(得分:1)

注意;自写答案以来,该问题已被编辑。在问题的前一个迭代中,分销商成员被定义为:

    public List<Distributor> Distributors(Distributor distributor)
    {
        List<Distributor> newList = new List<Distributor>();
        newList.Add(distributor);
        return newList;
    }

您的 CoverType(例如)是一个属性(字符串类型)

经销商看起来并没有什么不同:

public List<Distributor> Distributors { get; set; } = new();

..除了在初始化类的过程中创建一个新的是明智的,否则如果你尝试使用它,你会得到一个空引用异常。在现代 C# 中,如果编译器可以在左侧看到它,则不需要在右侧指定类型。如果您的 c# 较旧,则需要使用 new List<Distributor>();

您可以像添加任何普通列表一样添加;调用该属性并添加一个分发服务器:

someBook.Distributors.Add(someDistributor);