我有一个泛型类来表示结果或错误,但不能同时表示两者:
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/