'T'必须为非空值类型,才能将其用作参数'T'在泛型类型或方法'System.N

本文关键字:参数 方法 System 泛型类型 空值 类型 | 更新日期: 2023-09-27 18:15:13

为什么我在下面的代码中得到这个错误?

void Main()
{
    int? a = 1;
    int? b = AddOne(1);
    a.Dump();
}
static Nullable<int> AddOne(Nullable<int> nullable)
{
    return ApplyFunction<int, int>(nullable, (int x) => x + 1);
}
static Nullable<T> ApplyFunction<T, TResult>(Nullable<T> nullable, Func<T, TResult> function)
{
    if (nullable.HasValue)
    {
        T unwrapped = nullable.Value;
        TResult result = function(unwrapped);
        return new Nullable<TResult>(result);
    }
    else
    {
        return new Nullable<T>();
    }
}

'T'必须为非空值类型,才能将其用作参数'T'在泛型类型或方法'System.N

这段代码有几个问题。第一个是类型必须是可空的。可以通过指定where T: struct来表示。您还需要指定where TResult: struct,因为您也将其用作可空类型。

一旦你修复了where T: struct where TResult: struct,你还需要改变返回值类型(这是错误的)和其他一些事情。

在修正了所有这些错误并进行了简化之后,您最终得到了这样的结果:

static TResult? ApplyFunction<T, TResult>(T? nullable, Func<T, TResult> function)
                where T: struct 
                where TResult: struct
{
    if (nullable.HasValue)
        return function(nullable.Value);
    else
        return null;
}

请注意,您可以将Nullable<T>重写为T?,这使内容更具可读性。

你也可以把它写成一个语句使用?:,但我不认为它是可读的:

return nullable.HasValue ? (TResult?) function(nullable.Value) : null;

你可能想把它放到一个扩展方法中:

public static class NullableExt
{
    public static TResult? ApplyFunction<T, TResult>(this T? nullable, Func<T, TResult> function)
        where T: struct
        where TResult: struct
    {
        if (nullable.HasValue)
            return function(nullable.Value);
        else
            return null;
    }
}

然后你可以写这样的代码:

int? x = 10;
double? x1 = x.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(x1);
int? y = null;
double? y1 = y.ApplyFunction(i => Math.Sqrt(i));
Console.WriteLine(y1);

正如错误提示的那样,编译器不能保证T不是可空的。您需要向T添加约束:

static Nullable<T> ApplyFunction<T, TResult>(Nullable<T> nullable, 
    Func<T, TResult> function) : where T : struct 
                                 where TResult : struct