小编典典

类列表在控制台中始终作为类名称打印输出?

c#

好的,也许我只是累了什么,但我似乎无法弄清为什么这种情况一直在发生。

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

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

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

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

// - - - - - 编辑

感谢您的帮助。我想我不明白的是为什么它在我的TestClass中起作用,所以我只写了伪数据,而当真正的实现出现时,它却不起作用:

        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打印到控制台,而无需转换为字符串。但是,当我添加第二个元素时,它停止工作了。那就是我的困惑。


阅读 216

收藏
2020-05-19

共1个答案

小编典典

您应该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()返回代表当前对象的字符串。这就是为什么您得到您所描述的。

2020-05-19