想知道我的静态构造函数是否失败,如果扩展方法仍然有效,则抛出异常?记录器旨在帮助检测扩展方法中的问题。如果它们仍然无法工作,我将不得不尝试捕获并确保构造函数成功。我希望能够让它抛出异常,因为希望调用代码可以记录错误。 (这只是我正在考虑的示例代码)
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;
}
}
我做了搜索(希望这不是重复)并发现从静态构造函数中抛出异常通常不是很好。在大多数情况下,我认为这些类是可以实例化的,而不仅仅是所有扩展方法。
答案 0 :(得分:5)
想知道我的静态构造函数是否失败,如果扩展方法仍然有效,则抛出异常?
没有。如果任何类型的类型初始值设定项(无论是否使用静态构造函数)失败,则此类型基本上不可用。
很容易证明这一点......
using System;
static class Extensions
{
static Extensions()
{
Console.WriteLine("Throwing exception");
throw new Exception("Bang");
}
public static void Woot(this int x)
{
Console.WriteLine("Woot!");
}
}
class Test
{
static void Main()
{
for (int i = 0; i < 5; i++)
{
try
{
i.Woot();
}
catch (Exception e)
{
Console.WriteLine("Caught exception: {0}", e.Message);
}
}
}
}
输出:
Throwing exception
Caught exception: The type initializer for 'Extensions' threw an exception.
Caught exception: The type initializer for 'Extensions' threw an exception.
Caught exception: The type initializer for 'Extensions' threw an exception.
Caught exception: The type initializer for 'Extensions' threw an exception.
Caught exception: The type initializer for 'Extensions' threw an exception.