【问题标题】:Is there a built-in ExpectNonNull?有内置的 ExpectNonNull 吗?
【发布时间】:2023-01-12 18:33:13
【问题描述】:

在我的代码中,当某些东西被声明为可空时,但我希望它在运行时是非空的,我可以这样做:

someObject.ExpectNonNull().SomeMember

ExpectNonNull 是这样实现的:

[return: NotNull]
public static T ExpectNonNull<T>(
    [NotNull] this T? arg,
    [CallerArgumentExpression(nameof(arg))] string arg_name = ""
)
    where T : class
{
    if (arg is null)
        throw new ArgumentNullException(
            arg_name,
            $"The argument `{arg_name}` with type {typeof(T).Name} is expected to be non-null, but is null."
        );
    return arg;
}

(还有一个值类型的版本。)

.NET 本身是否有类似的内置功能?

【问题讨论】:

  • 您可以使用 null-forgiving 运营商。这将消除编译器警告,但仍会在运行时引发 nullref
  • 是你想要的吗someObject?.SomeMember

标签: c# .net .net-7.0


【解决方案1】:

从 .NET 6 开始,您至少可以使用 ArgumentNullException.ThrowIfNull一些你所追求的:

public void SomeMethod(string text)
{
    ArgumentNullException.ThrowIfNull(text);
    // Use text here, confident that it's not null
}

它不允许您使用那种流畅的方法,但在某些情况下,这就是您所需要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2021-05-12
    相关资源
    最近更新 更多