#if DEBUG用于异常处理

Kro*_*owi 4 c#

我有一个ChangeLanguage类库中的公共方法,应该被其他人使用,他们不知道源代码是什么,但知道它可以做什么.

public string ChangeLanguage(string language) 
{
    #if DEBUG
        // Check if the new language is not null or an empty string.
        language.ThrowArgumentNullExceptionIfNullOrEmpty("language", GetString("0x000000069"));
    #else
        if (string.IsNullOrEmpty(language))
            language = _fallbackLanguage;
    #endif 
}
Run Code Online (Sandbox Code Playgroud)

对我来说,检查是否language实际传递给方法看起来很明显,如果没有,则向开发人员抛出错误.这是一个非常小的性能损失,我认为最好不抛出异常,但只是在没有提供语言时使用后备语言.

我想知道这是一个好的设计方法,如果我应该继续在库中的其他地方使用它,就像这里:

    _appResDicSource = Path.Combine("\\" + _projectName + ";component", _languagesDirectoryName, _fileBaseName + "_" + language + ".xaml");
    _clsLibResDicSource = "\\Noru.Base;component\\Languages\\Language_" + language + ".xaml";

    ResourceDictionary applicationResourceDictionary;
    ResourceDictionary classLibraryResourceDictionary;

    try { applicationResourceDictionary = new ResourceDictionary { Source = new Uri(_appResDicSource, UriKind.RelativeOrAbsolute) }; }
    catch
    {
#if DEBUG
        throw new IOException(string.Format(GetString("1x00000006A"), _appResDicSource));
#else
        return ChangeLanguage(_fallbackLanguage);
#endif
    }
    try { classLibraryResourceDictionary = new ResourceDictionary { Source = new Uri(_clsLibResDicSource, UriKind.RelativeOrAbsolute) }; }
    catch
    {
#if DEBUG
        throw new IOException(string.Format(GetString("1x00000006B"), _clsLibResDicSource));
#else
        return ChangeLanguage(_fallbackLanguage);
#endif
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*exD 5

它取决于调用的语义,但我会考虑Debug.Fail(如果DEBUG没有定义,它将被删除):

public string ChangeLanguage(string language) 
{
    if (string.IsNullOrEmpty(language))
    {
        Debug.Fail("language is NOK");
        language = _fallbackLanguage;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,一方面,正如@OndrejTucny@poke所提到的,不希望为不同的构建配置提供不同的逻辑.它是正确的.

但另一方面,有些情况下您不希望应用程序因为轻微错误而在现场崩溃.但是,如果您无条件地忽略错误,即使在本地系统上也会降低检测错误的几率.

我不认为有一个通用的解决方案.一般情况下,您可能最终决定是否抛弃,无论是否记录,是否总是或有时添加断言.答案取决于具体情况.