想知道如果扩展方法仍然有效,我的静态构造函数是否失败并抛出异常?记录器旨在帮助检测扩展方法中的问题。如果它们仍然无法工作,我将不得不尝试 catch 并确保构造函数成功。我希望能够让它抛出异常,因为希望调用代码可以记录错误。(这只是类似于我正在考虑的示例代码)
public static class Extensions
{
private static readonly log4net.ILog log;
private const TIME_TO_CHECK;
static Extensions()
{
log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //could maybe throw exception
TIME_TO_CHECK = readInFromFile(); //could maybe throw exception }
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) {
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0) {
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
}
我确实四处搜索(希望这不是重复),发现从静态构造函数中抛出异常通常不是很好。在大多数情况下,我认为这些类是可以实例化的,而不仅仅是扩展方法。