【问题标题】:Static Constructor and Extension methods静态构造函数和扩展方法
【发布时间】:2023-03-10 08:36:01
【问题描述】:

想知道如果扩展方法仍然有效,我的静态构造函数是否失败并抛出异常?记录器旨在帮助检测扩展方法中的问题。如果它们仍然无法工作,我将不得不尝试 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;
    }
  }

我确实搜索过(希望这不是重复),发现从静态构造函数抛出异常通常不是很好。在大多数情况下,我认为这些类是可以实例化的,而不仅仅是所有扩展方法。

【问题讨论】:

  • 如果静态构造函数抛出异常,运行时将不会再次调用它,并且该类型将在程序运行的应用程序域的生命周期内保持未初始化状态。最常见的是,当静态构造函数无法实例化类型或静态构造函数中发生未处理的异常时,会引发 TypeInitializationException 异常。 ref

标签: c# static constructor


【解决方案1】:

想知道如果扩展方法仍然有效,我的静态构造函数是否失败并抛出异常?

没有。如果任何类型的类型初始值设定项(无论是否使用静态构造函数)失败,则该类型此后基本上无法使用。

很容易证明这一点......

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.

【讨论】:

  • 谢谢你尝试它会很聪明。希望它可以帮助别人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 2013-07-24
  • 2011-03-01
  • 1970-01-01
相关资源
最近更新 更多