seb*_*ibu 3 c# extension-methods nullable
我想编写一个通用扩展方法,如果没有值则抛出错误。所以我想要这样的东西:
public static T GetValueOrThrow(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
Run Code Online (Sandbox Code Playgroud)
知道这是否有效吗?我错过了什么?
我还想出了:
public static T GetValueOrThrow<T>(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
Run Code Online (Sandbox Code Playgroud)
现在 C# 抱怨候选者:类型 T 必须是不可为 null 的值类型才能将其用作泛型类型或方法 Nullable 中的参数 T
这与比较无关。
public static T GetValueOrThrow<T>(this Nullable<T> candidate) where T : struct // can be this T? as well, but I think with explicit type is easier to understand
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
Run Code Online (Sandbox Code Playgroud)
where T : class约束为引用类型,可以为空,但 HasValue 是Nullable 类型的属性(它是值类型以及 T)。