可空泛型扩展方法

Nullable generic extension method

我想编写一个通用扩展方法,如果没有值则抛出错误。所以我想要这样的东西:

public static T GetValueOrThrow(this T? candidate) where T : class
        {
            if (candidate.HasValue == false)
            {
                throw new ArgumentNullException(nameof(candidate));
            }

            return candidate.Value;
        }
  1. C# 无法识别 T:找不到类型或名称空间名称"T"
  2. C# 无法识别哪里:非泛型声明不允许约束

知道这是否有效吗?我错过了什么?

我也想出了:

public static T GetValueOrThrow<T>(this T? candidate) where T : class
        {
            if (candidate.HasValue == false)
            {
                throw new ArgumentNullException(nameof(candidate));
            }

            return candidate.Value;
        }

现在 C# 抱怨候选人:类型 T 必须是不可空值类型才能将其用作泛型类型或方法中的参数 T Nullable

这与比较无关

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;
}

where T : class约束为引用类型,可以为null,但是HasValue是Nullable type的属性(既是值类型又是T)。