Ich 有一个方法 ThrowNull 覆盖有DoesNotReturn 属性,表明该方法永远不会返回。
[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);
Run Code Online (Sandbox Code Playgroud)
但是,它似乎不起作用(按预期)
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
}
Run Code Online (Sandbox Code Playgroud)
为什么?
DoesNotReturn 是否没有忽略放置 return 语句的必要性,因为它只是避免警告?
DoesNotReturn 属性仅具有声明性字符,并且不会使您免于将 return 语句放入非 void 方法/属性
直接在代码中使用 throw 并从其他地方获取异常。(这在反编译的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);
}
Run Code Online (Sandbox Code Playgroud)