C# 可空泛型扩展方法

C# 可空泛型扩展方法,c#,extension-methods,nullable,C#,Extension Methods,Nullable,我想编写一个通用扩展方法,如果没有值,它会抛出一个错误。所以我想要这样的东西: public static T GetValueOrThrow(this T? candidate) where T : class { if (candidate.HasValue == false) { throw new ArgumentNullException(nameof(candidate));

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

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

            return candidate.Value;
        }
  • C#无法识别T:找不到类型或命名空间名称“T”
  • C#没有认识到:不允许对非泛型声明使用约束
  • 知道这是否有效吗?我错过了什么

    我还提出:

    public static T GetValueOrThrow<T>(this T? candidate) where T : class
            {
                if (candidate.HasValue == false)
                {
                    throw new ArgumentNullException(nameof(candidate));
                }
    
                return candidate.Value;
            }
    
    public static T GetValueOrThrow(此T?候选对象),其中T:class
    {
    if(candidate.HasValue==false)
    {
    抛出新的ArgumentNullException(nameof(候选者));
    }
    返回候选值;
    }
    
    现在C#抱怨候选者:类型T必须是不可为null的值类型,才能将其用作泛型类型或可为null的方法中的参数T

    这与比较无关。

    public static T GetValueOrThrow(这个可为空的候选者),其中T:struct//可以是这个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;
    }
    
    { if(candidate.HasValue==false) { 抛出新的ArgumentNullException(nameof(候选者)); } 返回候选值; }

    其中T:class
    约束到引用类型,可以为null,但HasValue是的属性(它是值类型,也是T)。

    这个T?
    毫无意义,因为类根据定义可以为null。
    其中T:struct
    ,你的意思是说。你为什么想要那个扩展?这是默认行为,只需使用
    candidate.Value
    ,如果没有值,对传入的错误感到兴奋。阅读Eric Lippert的文章,首先找出这是一个坏主意的原因。可能重复