类列表在控制台中不断打印为类名? [英] Class List Keeps Printing Out As Class Name In Console?
问题描述
好吧,所以也许我只是累了或者什么,但我似乎无法弄清楚为什么这种情况一直发生.
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 I have.
当我打印到控制台进行调试时,它只是打印为:
When I print to the console for debugging, it simply prints out as:
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<SharePrices> newList = new List<SharePrices>();
newList.Add(derpList);
newList.ForEach(Console.WriteLine);
}
}
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
}
请原谅我的命名习惯.这只是个人项目的线框图.
Please excuse my naming conventions. This is just a wireframe for a personal project.
//-----------编辑
//----------Edit
感谢大家的帮助.我想我不明白的是为什么它在我的 TestClass 中工作我写的只是玩弄假数据,当真正的实现来时它不起作用:
Thanks for the help guys. I guess what I wasn't understanding is why it was working in my TestClass I wrote just playing with fake data, and when the real implementation came it didn't work:
public static void FindWindowDays()
{
DateTime currentDate = DateTime.Now;
var dates = new List<DateTime>();
for (var dt = currentDate.AddDays(-windowDays); dt <= currentDate; dt = dt.AddDays(1))
{
dates.Add(dt);
}
var ascending = dates.OrderByDescending(i => i);
foreach (var datesyo in ascending)
{
Console.WriteLine(datesyo);
}
}
这似乎可以很好地将 DateTime 打印到控制台,而无需转换为字符串.但是当我添加第二个元素时,它停止工作.这就是我感到困惑的地方.
This seemed to work fine printing the DateTime to console without converting to string. But when I added the second element, it stopped working. That's where I got confuddled.
推荐答案
你应该按照你想要的格式覆盖你的类的 ToString()
,例如这样:
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);
}
}
默认情况下,没有覆盖,ToString()
返回一个代表当前对象的字符串.所以这就是为什么你得到你所描述的.
By default, without overriding, ToString()
returns a string that represents the current object. So that's why you get what you described.
这篇关于类列表在控制台中不断打印为类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!