我最近正在使用一个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#陷阱分类会很有用。
不是最糟糕的,但还没被提起。工厂方法作为参数传递给System.Collections.Concurrent方法可以被多次调用,即使只使用了一个返回值。考虑到. net在线程原语中多么强烈地试图保护您不受虚假唤醒的影响,这可能会让您感到惊讶。
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ValueFactoryBehavingBadlyExample
{
class Program
{
static ConcurrentDictionary<int, int> m_Dict = new ConcurrentDictionary<int, int>();
static ManualResetEventSlim m_MRES = new ManualResetEventSlim(false);
static void Main(string[] args)
{
for (int i = 0; i < 8; ++i)
{
Task.Factory.StartNew(ThreadGate, TaskCreationOptions.LongRunning);
}
Thread.Sleep(1000);
m_MRES.Set();
Thread.Sleep(1000);
Console.WriteLine("Dictionary Size: " + m_Dict.Count);
Console.Read();
}
static void ThreadGate()
{
m_MRES.Wait();
int value = m_Dict.GetOrAdd(0, ValueFactory);
}
static int ValueFactory(int key)
{
Thread.Sleep(1000);
Console.WriteLine("Value Factory Called");
return key;
}
}
}
(可能)输出:
Value Factory Called
Value Factory Called
Value Factory Called
Value Factory Called
Dictionary Size: 0
Value Factory Called
Value Factory Called
Value Factory Called
Value Factory Called