将课程与字典连接

时间:2018-08-31 11:46:54

标签: c#

我正在尝试将类添加到字典中,但是当我尝试将其写入控制台时,它只会写:

  

[1,DictionaryTest.Program + book]

我要它写:

  

[1,迈克尔,这本书]

这是我创建字典并尝试在控制台上显示它的主要方法:

static void Main(string[] args)
    {
        Dictionary<int,book> books = new Dictionary<int, book>();

        var book1 = new book("Michael","The Book"); 


        books.Add(1,book1);

        foreach(KeyValuePair<int,book> b in books)
        {
            Console.WriteLine(b);
        }

    }

这是带有两个字符串的“书”类

public class book
    {
        private string Author;
        private string Title;

        public book(string Author, string Title)
        {
            this.Author = Author;
            this.Title = Title;
        }
    }

希望可以为您提供帮助 -迈克尔

4 个答案:

答案 0 :(得分:3)

覆盖类的方法ToString()

  

创建自定义类或结构时,应覆盖   ToString方法,以便提供有关您的类型的信息   客户代码。

如果不这样做,.NET将不知道要显示哪些属性,并且默认情况下它将显示类的名称

public class book
    {
        public override string ToString(){
           return $"{Author} , {Title}";
    }
}

答案 1 :(得分:0)

如果将AuthorTitle设为公开,则可以通过以下方式设置输出格式:

Console.WriteLine($"[{b.Key}, {b.Value.Author}, {b.Value.Title}]");

答案 2 :(得分:0)

蒂埃里五世的答案就是要走的路。一个类不仅会自己打印,它还需要知道要打印什么,当您需要它作为字符串时。

另一种选择是公开yourBuffer[x][y] = yourBuffer[y][x]Author属性,并使用Title实例的属性,如下所示:

Book

答案 3 :(得分:0)

您需要重写ToString方法。

    class Program
{
    static void Main(string[] args)
    {
        Dictionary<int, book> books = new Dictionary<int, book>();

        var book1 = new book("Michael", "The Book");


        books.Add(1, book1);

        foreach (KeyValuePair<int, book> b in books)
        {
            Console.WriteLine(b);
        }
    }
}
public class book
{
    private string Author;
    private string Title;

    public book(string Author, string Title)
    {
        this.Author = Author;
        this.Title = Title;
    }

    //Overriding the ToString method.
    override
    public String ToString()
    {
        return Author + " , " + Title;
    }
}