class级列表在控制台中作为class级名称保持打印?

好吧,也许我只是累了或者其他什么,但我似乎无法弄清楚为什么会这样。

对于我拥有的数据库中的数据点,每天都会调用以下代码。

当我打印到控制台进行调试时,它只是打印出来:

NamespaceName.SharePrices 

不知道发生了什么。

  public void OnData(TradeBars data) { decimal price = data["IBM"].Price; DateTime today = data["IBM"].Time; //--------------Below works fine. if (today.Date >= nextTradeDate.Date) { MarketOnOpenOrder("IBM", 50); Debug("Purchased Stock"); nextTradeDate = today.AddDays(1); MarketOnOpenOrder("IBM", -25); } var derpList = new SharePrices { theDate = today, sharePrice = price }; List newList = new List(); newList.Add(derpList); newList.ForEach(Console.WriteLine); } } public class SharePrices { public DateTime theDate { get; set; } public decimal sharePrice { get; set; } } 

请原谅我的命名约定。 这只是个人项目的线框。

// – – – – – 编辑

谢谢你的帮助。 我想我不理解的是为什么它在我的TestClass中工作我写的只是玩假数据,当真正的实现来了它不起作用:

  public static void FindWindowDays() { DateTime currentDate = DateTime.Now; var dates = new List(); for (var dt = currentDate.AddDays(-windowDays); dt  i); foreach (var datesyo in ascending) { Console.WriteLine(datesyo); } } 

这似乎可以很好地将DateTime打印到控制台而无需转换为字符串。 但是当我添加第二个元素时,它就停止了工作。 这就是我困惑的地方。

您应该根据需要以格式覆盖类的ToString() ,例如:

 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); } } 

默认情况下,不覆盖, ToString()返回表示当前对象的字符串。 这就是为什么你得到你所描述的。

除了类名,C#对SharePrices 。 如果你想要它显示特定的东西,你需要覆盖ToString()方法,如下所示:

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

当然,您可以根据自己的喜好对其进行格式化,这就是它的美妙之处。 如果您只关心价格而不关心日期,则只return sharePrice

在类上调用Console.WriteLine时,它将自动调用该类的ToString()方法。

如果要打印详细信息,则需要在类中重写ToString() ,或者使用要打印的每个属性调用Console.WriteLine

这将工作,而不必使用.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(); newList2.Add(sp); newList2.ForEach(itemX => Console.WriteLine("Date: {0} Sharprice: {1}",sp.theDate, sp.sharePrice));