c# - 绑定(bind)到值类型的通用类型参数 - 使它们可以为空

标签 c# generics nullable boxing nullable-reference-types

我有一个泛型类来表示结果或错误,但不能同时表示两者:

public class Result<TValue, TError>
    where TValue : notnull
    where TError : notnull
{
    private readonly bool succeeded;
    private readonly TValue? value;
    private readonly TError? error;

    public static Result<TValue, TError> Success(TValue value) =>
        new(true, value ?? throw new ArgumentNullException(nameof(value)), default);

    public static Result<TValue, TError> Failure(TError error) =>
        new(false, default, error ?? throw new ArgumentNullException(nameof(error)));

    protected Result(bool succeeded, TValue? value, TError? error)
    {
        this.succeeded = succeeded;
        this.value = value;
        this.error = error;
    }
    
    public bool Successful(
        [NotNullWhen(true)] out TValue? value,
        [NotNullWhen(false)] out TError? error)
    {
        if (succeeded)
        {
            value = this.value!;
            error = default;
            return true;
        }
        else
        {
            value = default;
            error = this.error!;
            return false;
        }
    }
}

这符合我对类(class)的要求。例如,如果 TValue 为 object,则 value 字段和 value 参数为 object?。但是,我意识到,当泛型类型参数是值类型时,用 ? 修饰它不会使其成为 Nullable。这可能是因为这样做会更改基础类型,而不仅仅是评论其可为空性。有没有办法引用泛型类型的 Nullable 版本?

最佳答案

这是语言限制。 请参阅official docs

If the type argument for T is a value type, T? references the same value type, T. For example, if T is an int, the T? is also an int.

关于c# - 绑定(bind)到值类型的通用类型参数 - 使它们可以为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72543817/

相关文章:

c# - WCF 服务响应中的意外标记名称

java - 通用 ConstraintViolations 集的异常

C11 - 通用选择中的枚举

c# - 模棱两可的调用匹配困惑

c# - 将 Base64 编码的 CSS 图片上传到 Asp.Net MVC/Web Api

c# - 引用值的 'Type'存放在内存的什么地方?

c# - WPF 中的基类 DependencyProperty 值更改

swift - 如何在运行时确定泛型变量的值?

entity-framework - 为什么 null 和对 null 的引用不是一回事

objective-c - 在 Swift 中检查 nil 的非可选值