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


当前回答

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

其他回答

Linq2SQL:接口成员的映射[…]不支持。

如果对实现接口的对象执行Linq2Sql查询,则会得到非常奇怪的行为。假设你有一个类MyClass,它实现了一个接口IHasDescription,这样:

public interface IHasDescription {
  string Description { get; set; }
}

public partial class MyClass : IHasDescription { }

(MyClass的另一半是一个Linq2Sql生成的类,包括属性Description。)

现在你写一些代码(这通常发生在泛型方法中):

public static T GetByDescription<T>(System.Data.Linq.Table<T> table, string desc) 
  where T : class, IHasDescription {
  return table.Where(t => t.Description == desc).FirstOrDefault();
}

编译正常-但你会得到一个运行时错误:

NotSupportedException: The mapping of interface member IHasDescription.Description is not supported.

现在该怎么办呢?好吧,这真的很明显:只需将==更改为.Equals(),这样:

return table.Where(t => t.Description.Equals(desc)).FirstOrDefault();

现在一切都好了!

在这里看到的。

private int myVar;
public int MyVar
{
    get { return MyVar; }
}

心想。你的应用在没有堆栈跟踪的情况下崩溃了。这种事经常发生。

(请注意getter中的大写MyVar而不是小写MyVar。)

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

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

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

到目前为止我最糟糕的一个,我今天才想出来……如果你重写object。Equals(object obj),你会发现:

((MyObject)obj).Equals(this);

与以下行为不同:

((MyObject)obj) == this;

一个会调用你的覆盖函数,另一个不会。

如果你正在为MOSS编写代码,你以这种方式获得一个站点引用:

SPSite oSiteCollection = SPContext.Current.Site;

之后在你的代码中你说:

oSiteCollection.Dispose();

从MSDN:

If you create an SPSite object, you can use the Dispose method to close the object. However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method or Site property (for example, SPContext.Current.Site), do not use the Dispose method to close the object, but instead allow Windows SharePoint Services or your portal application to manage the object. For more information about object disposal, see Best Practices: Using Disposable Windows SharePoint Services Objects.

每个MOSS程序员都会遇到这种情况。