如何使用方法将对象添加到私有列表?

时间:2019-05-27 12:25:33

标签: c# list object add private

您可以看到我创建的列表是私有的,我希望能够向列表中添加对象以及通过方法AddBook()和ShowBooks()向用户显示该列表。

public class Library
{
    private List<Book> Books = new List<Book>();       

    public static void AddBook()
    {
    }

    public static void ShowBooks()
    {
        foreach (Book item in Books)  
        //This foreach-loop doesn't work since its a private list.
        {
            Console.WriteLine("Books found");
        }
    }
}

循环无效,因为“引用非静态字段,方法或属性需要对象引用”。

3 个答案:

答案 0 :(得分:0)

如果您不想在books集合上使用static,请执行以下操作:

public class Library
{
    private List<Book> Books = new List<Book>();       

    public void AddBook()
    {
    }

    public void ShowBooks()
    {
        var library = new Library();
        foreach (Book item in Books)  
        {
            //This foreach-loop doesn't work since its a private list.
            library.Books.Add(item);
            Console.WriteLine("Books found");
        }
    }
}

答案 1 :(得分:0)

如果您想使用静态方法,可以尝试一下

using System;

使用System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        Library.AddBook(new Book(){name = "test"});
        Library.AddBook(new Book(){name = "test1"});

        Library.ShowBooks();
    }
}

public class Book
{
    public string name;
}

public static class Library
{
    private static List<Book> Books = new List<Book>();

    public static void AddBook(Book b1)
    {
        Books.Add(b1);
    }

    public static void ShowBooks()
    {
        foreach (Book item in Books)  
        //This foreach-loop doesn't work since its a private list.
        {
            Console.WriteLine(item.name);
        }
    }
}

没有静态方法,您可以尝试

using System;
using System.Collections.Generic;


public class Program
{
    public static void Main()
    {
        Library l1 = new Library();
        l1.AddBook(new Book(){name = "test"});
        l1.AddBook(new Book(){name = "test1"});

        l1.ShowBooks();
    }
}


public class Book
{
    public string name;
}

public  class Library
{
    private  List<Book> Books = new List<Book>();

    public  void AddBook(Book b1)
    {
        Books.Add(b1);
    }

    public  void ShowBooks()
    {
        foreach (Book item in Books)  
        //This foreach-loop doesn't work since its a private list.
        {
            Console.WriteLine(item.name);
        }
    }
}

答案 2 :(得分:-1)

问题在于您的List实例是非静态的,而您的方法却是非静态的。您必须将List更改为静态,或者将方法更改为非静态。按照良好的OO设计,我建议您从方法中删除static修饰符。我还对您的列表应用了一个只读修饰符,并将其更改为ICollection,因为您似乎不需要索引访问。并应用了一些常见的命名模式。

public class Library
{
    private readonly ICollection<Book> _books = new List<Book>();       


    public void AddBook(Book book)
    {
        _books.Add(book);
    }

    public void ShowBooks()
    {
        foreach (Book item in _books)  
        {
            Console.WriteLine("Books found");
        }
    }
}