为什么我在以下代码中收到此错误?
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);