在异常静态构造函数 [英] Exception in static constructor

查看:92
本文介绍了在异常静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经挖SO周围的答案,这一点,最好的一个我能找到到目前为止的这里,但是,这种向与静态构造函数实例减速; 。我只使用类静态

I've dug around SO for an answer to this, and the best one I can find so far is here, however that is geared toward instances with static constructors; I'm only using the class statically.

我的代码:

public static class MailHelper {

    private static string mailHost;

    static MailHelper() {

        var mailSettings = ConfigurationManager.GetSection("MailSettings") as NameValueCollection;
        if (null == mailSettings) {
            throw new ConfigurationErrorsException("Missing Mail Settings in the configuration file");
        }

        mailHost = ConfigurationManager.AppSettings["mailHost"];
        if (null == mailHost) {
            throw new ConfigurationErrorsException("Missing mailHost setting in the configuration file");
        }

    }

    public static void SendMail(MailMessage Message) {
        ...
    }

}


try {
    MailHelper.SendMail(Message);
}
catch (ConfigurationErrorsException exc) {
    ...
}

//  ???    
MailHelper.SendMail(Message);


.



因此​​,如果静态构造函数抛出一个异常,它第一次被称为,会发生什么我第二次尝试?访问静态的SendMail()方法。

So if the static constructor throws an exception the first time it's called, what happens the second time I try to access the static SendMail() method?

PS:很抱歉,如果你不喜欢Stroustrup的版本K&放大器; R撑造型,但不要只是编辑自己的帖子改变括号您的首选奥尔曼风格。谢谢

PS: Sorry if you don't like Stroustrup's version of K&R brace styling, but don't edit my post just to change the braces to your preferred Allman style. Thanks.

推荐答案

另外两个答案都好回答您的直接的问题 - 这里有一个metaanswer - 你应该会抛出异常当检测方法,该构造元件被未填充的,而不是在构造。恕我直言,未配置是在构造阶段的元素,只是没有在Sendmail的时间有效配置状态。这将回避这个整个问题。

The other two answers are good answers to your direct question - here's a metaanswer - you should be throwing the exception in the method when you detect that the configuration elements are not populated, rather than in the constructor. IMHO, "not configured" is a valid configuration state for those elements at the constructor phase, just not at SendMail time. That will sidestep this whole problem.

这篇关于在异常静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆