简体   繁体   English

为什么 *DoesNotReturnAttribute* 没有按预期工作?

[英]Why is *DoesNotReturnAttribute* not working as expected?

Ich have a method ThrowNull covered with DoesNotReturn attribute which indicates that this method will never return.我有一个包含 DoesNotReturn 属性的 ThrowNull 方法,该属性指示此方法永远不会返回。

[DoesNotReturn]
public static void ThrowNull([InvokerParameterName] string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") => throw new ArgumentException(AddMethodName(customErrorText != null ? customErrorText.InsertArgs(argName) : Strings.ArgumentMustNotBeNullArgumentTemplate.InsertArgs(callerName), callerName), customErrorText == null ? argName : null);

but, it does not seem to work (as intended)但是,它似乎不起作用(按预期)

public static T ThrowIfNullOrGet<T>([MaybeNull, NotNullIfNotNull("source")] this T source, string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") where T : class
{
    if (source != null)
        return source;

    Requires.ThrowNull(argName, customErrorText, callerName);
    return default; // still necessary to prevent compile error
}

Why?为什么?

Does DoesNotReturn not omit the necessity to put an return statement as it only avoids warnings? DoesNotReturn 不会忽略放置返回语句的必要性,因为它只会避免警告吗?

The DoesNotReturn attribute has only declarative character and does not save you from putting return statement to non void methods/properties DoesNotReturn 属性仅具有声明性字符,并且不会使您免于将 return 语句置于非 void 方法/属性中

use throw directly in your code and get the exception from somewhere else.直接在代码中使用 throw 并从其他地方获取异常。 (this can be seen often in decompiled MS code) (这可以在反编译的 MS 代码中经常看到)

public static T GetOrThrowIfNull<T>([MaybeNull, NotNullIfNotNull("source")] this T source, string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") where T : class
{
    if (source != null)
        return source;

    throw Exceptions.ArgumentNull(argName, customErrorText, callerName);
}

If you're using throw helpers then the throw helper should do the throw, not the method calling the throw helper.如果您使用的是 throw 助手,那么 throw 助手应该执行 throw,而不是调用 throw 助手的方法。 The right way to write this is to invert the if condition:正确的写法是反转if条件:

public static T GetOrThrowIfNull<T>([MaybeNull, NotNullIfNotNull("source")] this T source, string argName, string? customErrorText = null, [CallerMemberName] string callerName = "") where T : class
{
    if (source == null)
        Requires.ThrowNull(argName, customErrorText, callerName);

    return source;
}

It is good practice to do validation and exception throwing at the beginning of the method.在方法的开头进行验证和异常抛出是一种很好的做法。 It lets you reduce the nesting of the actual functionality of the method, and like shown above, lets you properly use throw helpers.它可以让您减少方法实际功能的嵌套,并且如上所示,可以让您正确使用 throw helpers。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM