Class List Keeps Printing Out As Class Name In Console?

前端 未结 4 729
北荒
北荒 2020-11-27 09:02

Ok, so maybe I\'m just tired or something but I can\'t seem to figure out why this keeps happening.

The code below is called every day for a data point in a database

相关标签:
4条回答
  • 2020-11-27 09:12

    You should override ToString() for your class in format as you want, for example like this:

    public class SharePrices
    {
        public DateTime theDate { get; set; }
        public decimal sharePrice { get; set; }
    
        public override string ToString()
        {
            return String.Format("The Date: {0}; Share Price: {1};", theDate, sharePrice);
        }
    }
    

    By default, without overriding, ToString() returns a string that represents the current object. So that's why you get what you described.

    0 讨论(0)
  • 2020-11-27 09:14

    When you call Console.WriteLine on a class, it will call the ToString() method on that class automatically.

    If you want to print the details out, you will over need to override ToString() in your class, or call Console.WriteLine with each property you want to print out.

    0 讨论(0)
  • 2020-11-27 09:14

    this will work without having to use .ToString()

    public class SharePrices
    {
        public DateTime theDate { get; set; }
        public decimal sharePrice { get; set; }
    }
    
    SharePrices sp = new SharePrices() { theDate = DateTime.Now, sharePrice = 10 };
    
    var newList2 = new List<SharePrices>();
    newList2.Add(sp);
    newList2.ForEach(itemX => Console.WriteLine("Date: {0} Sharprice: {1}",sp.theDate, sp.sharePrice));
    
    0 讨论(0)
  • 2020-11-27 09:31

    C# doesn't know anything about the SharePrices other than the class name. If you want it to display something specific, you will need to override the ToString() method like so:

    public override string ToString()
    {
        return "SharePrice: " + theDate.ToString() + ": " + sharePrice.ToString();
    }
    

    Of course, you can format it however you like, that is the beauty of it. If you only care about the price and not the date, only return the sharePrice.

    0 讨论(0)
提交回复
热议问题