c# - 静态构造函数和扩展方法

标签 c# static constructor

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

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

最佳答案

Wondering if my static constructor fails and throws exception if the extension methods would still work?

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

证明这个很容易...

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.

关于c# - 静态构造函数和扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17492790/

相关文章:

c# - Azure Cosmos DB 添加字符串数组的复合索引

java - Activity 类中的静态字段是否保证比创建/销毁周期更长?

c++ - 你怎么知道 main 是否已经退出?

c++ - 有效地初始化 const std::vector 类成员

java - PowerMock 的 expectNew() 没有像预期的那样模拟构造函数

c# - "CS1513: } Expected"错误

c# - 开发游戏服务器的好语言?

c# - 使用 ENTity Framework 查询填充 DTO 类 List<>

c - 返回指向静态局部变量的指针

c++ - 在默认构造函数签名中返回对象与引用