加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 类型“T”必须是不可为空的值类型,以便在通用类型或方法“

发布时间:2020-12-15 04:05:35 所属栏目:百科 来源:网络整理
导读:为什么我在以下代码中收到此错误? void Main(){ int? a = 1; int? b = AddOne(1); a.Dump();}static Nullableint AddOne(Nullableint nullable){ return ApplyFunctionint,int(nullable,(int x) = x + 1);}static NullableT ApplyFunctionT,TResult(Nullabl
为什么我在以下代码中收到此错误?
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读