在c#中显示不同类型的列表的正确方法是什么?

时间:2019-07-07 20:29:21

标签: c#

好的,所以基本上我正在创建一个需要创建,读取,更新和删除的项目。但是,我不是指数据库服务器,而是类型列表。我试图弄清楚如何显示Dvd类型的列表。我的第一个目标是能够显示DVD列表,然后再开始执行update和delete方法。这是我的课程:

DvdController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;

namespace DvdManager.Controllers
{
    public class DvdController
    {
        List<Dvd> Dvds = new List<Dvd>(10);       


        public void Run()
        {
            Console.WriteLine("Welcome To Dvd Manager");

            CreateDvd();
        }

        private void CreateDvd()//Create
        {
            Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
            Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
            Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
            DisplayDvds();
        }

        private void DisplayDvds() //Read List<Dvd> dvds
        {
            for (int i = 0; i < Dvds.Count; i++)
            {
                Console.WriteLine(Dvds[i]);
            }
        }

        private void SearchDvds() //List
        {

        }

        private void EditDvd(int id, Dvd dvd) //Update
        {

        }

        private void RemoveDvd(int id) //Delete
        {


        }
    }
}

Dvd.cs

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

namespace DvdManager.Models
{
    public class Dvd
    {
        public Dvd(int id, string title, int releaseyear, string director, float rating)
        {
            Id = id;
            Title = title;
            ReleaseYear = releaseyear;
            Director = director;
            Rating = rating;
        }

        int Id { get; }
        string Title { get; set; }
        int ReleaseYear { get; set; }
        string Director { get; set; }
        float Rating { get; set; }


    }
}

问题在于它显示:

  

DvdManager.Models.Dvd

但是,我要执行的操作是按ID,标题,发行年份,导演,等级显示其值。我如何成功做到这一点?

1 个答案:

答案 0 :(得分:2)

您正在打印类的ToString返回的默认字符串表示形式。如果需要其他输出,则可以自己覆盖ToString。例如:

public override string ToString()
{
   return string.Format
              ("DVD [Id: {0}; Title: {1}; ReleaseYear: {2}; Director: {3}; Rating: {4}]",
               Id, Title, ReleaseYear, Director, Rating);
}