我最近正在使用一个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#陷阱分类会很有用。
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();
现在一切都好了!
在这里看到的。
如果你正在为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程序员都会遇到这种情况。