我最近正在使用一个DateTime对象,并写了这样的东西:

DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date! WTF?

AddDays()的智能感知文档说它在日期后添加了一天,但它并没有这样做——它实际上返回了一个添加了一天的日期,所以你必须这样写:

DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date

这个问题以前已经困扰过我很多次了,所以我认为将最糟糕的c#陷阱分类会很有用。


当前回答

Dictionary<,>: "返回项的顺序未定义"。这很可怕,因为它有时会咬你一口,但会对其他人起作用,如果你只是盲目地认为Dictionary会表现得很好(“为什么不呢?”我想,是List做的”),在你最终开始质疑你的假设之前,你真的必须深入了解它。

(这里也有类似问题。)

其他回答

只是发现了一个奇怪的问题,让我在调试中困了一段时间:

对于一个可为空的int,可以增加null值而不抛出异常,并且该值保持为空。

int? i = null;
i++; // I would have expected an exception but runs fine and stays as null

一些代码:

        List<int> a = new List<int>();
        for (int i = 0; i < 10; i++)
        {
            a.Add(i);
        }

        var q1 = (from aa in a
                  where aa == 2
                  select aa).Single();

        var q2 = (from aa in a
                  where aa == 2
                  select aa).First();

q1 -在这个查询中检查List中的所有整数; Q2 -检查整数,直到找到“正确的”整数。

重载==操作符和非类型化容器(数组列表、数据集等):

string my = "my ";
Debug.Assert(my+"string" == "my string"); //true

var a = new ArrayList();
a.Add(my+"string");
a.Add("my string");

// uses ==(object) instead of ==(string)
Debug.Assert(a[1] == "my string"); // true, due to interning magic
Debug.Assert(a[0] == "my string"); // false

解决方案?

总是使用字符串。当比较字符串类型时等于(a, b) 使用像List<string>这样的泛型来确保两个操作数都是字符串。

前几天我看到了这个帖子,我觉得它很晦涩,对那些不知道的人来说很痛苦

int x = 0;
x = x++;
return x;

因为这将返回0,而不是大多数人期望的1

如果算上ASP。NET,我得说webforms的生命周期对我来说是一个相当大的难题。我花了无数的时间调试写得很糟糕的webforms代码,只是因为很多开发人员真的不明白什么时候使用哪个事件处理程序(很遗憾,包括我在内)。