我最近正在使用一个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#陷阱分类会很有用。


当前回答

MemoryStream.GetBuffer() vs MemoryStream.ToArray()。前者返回整个缓冲区,后者只返回使用的部分。讨厌的东西。

其他回答

也许不是最糟糕的,但是。net框架的某些部分使用角度,而其他部分使用弧度(智能感知出现的文档从来没有告诉你是哪个,你必须访问MSDN才能找到)

所有这些都可以通过使用一个Angle类来避免……

LinqToSql批处理速度随着批处理大小的平方而变慢

以下是我探索这个问题的问题(和答案)。

In a nutshell, if you try to build up too many objects in memory before calling DataContext.SubmitChanges(), you start experiencing sluggishness at a geometric rate. I have not confirmed 100% that this is the case, but it appears to me that the call to DataContext.GetChangeSet() causes the data context to perform an equivalence evaluation (.Equals()) on every single combination of 2 items in the change set, probably to make sure it's not double-inserting or causing other concurrency issues. Problem is that if you have very large batches, the number of comparisons increases proportionately with the square of n, i.e. (n^2+n)/2. 1,000 items in memory means over 500,000 comparisons... and that can take a heckuva long time.

为了避免这种情况,您必须确保对于预计有大量项目的任何批处理,您都在事务边界内完成整个工作,在创建每个项目时保存它,而不是在最后进行一次大保存。

Linq-To-Sql和数据库/本地代码歧义

有时Linq无法判断某个方法是要在DB上执行还是在本地代码中执行。

请看这里和这里的问题陈述和解决方案。

我来这个派对有点晚了,但我最近有两个问题都困扰着我:

DateTime决议

Ticks属性以千万分之一秒(100纳秒块)为单位测量时间,但是分辨率不是100纳秒,而是大约15毫秒。

这段代码:

long now = DateTime.Now.Ticks;
for (int i = 0; i < 10; i++)
{
    System.Threading.Thread.Sleep(1);
    Console.WriteLine(DateTime.Now.Ticks - now);
}

将给你一个输出(例如):

0
0
0
0
0
0
0
156254
156254
156254

类似地,如果查看DateTime.Now。毫秒,您将得到以15.625毫秒为单位的四舍五入块的值:15、31、46等等。

这种特殊的行为因系统而异,但是在这个日期/时间API中还有其他与解析相关的问题。


路径。结合

一种组合文件路径的好方法,但它并不总是按您期望的方式运行。

如果第二个参数以\字符开头,它不会给你一个完整的路径:

这段代码:

string prefix1 = "C:\\MyFolder\\MySubFolder";
string prefix2 = "C:\\MyFolder\\MySubFolder\\";
string suffix1 = "log\\";
string suffix2 = "\\log\\";

Console.WriteLine(Path.Combine(prefix1, suffix1));
Console.WriteLine(Path.Combine(prefix1, suffix2));
Console.WriteLine(Path.Combine(prefix2, suffix1));
Console.WriteLine(Path.Combine(prefix2, suffix2));

给出如下输出:

C:\MyFolder\MySubFolder\log\
\log\
C:\MyFolder\MySubFolder\log\
\log\

对于LINQ-to-SQL和LINQ-to-Entities

return result = from o in table
                where o.column == null
                select o;
//Returns all rows where column is null

int? myNullInt = null;
return result = from o in table
                where o.column == myNullInt
                select o;
//Never returns anything!

这里有一个LINQ-to-Entites的错误报告,尽管他们似乎不经常检查这个论坛。也许有人也应该为LINQ-to-SQL申请一个?