微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 类型“T”必须是不可为空的值类型,以便在通用类型或方法“System.Nullable”中将其用作参数“T”

为什么我在以下代码中收到此错误
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:struct来表达.您还需要指定TResult:struct的位置,因为您也将它用作可空类型.

一旦你修复了T:struct where TResult:struct你也需要改变返回值类型(这是错误的)和一些其他的东西.

在修复所有这些错误并简化之后,您可以这样做:

static TResult? ApplyFunction<T,TResult>(T? nullable,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,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);

原文地址:https://www.jb51.cc/csharp/92751.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐