【发布时间】:2012-07-09 19:22:27
【问题描述】:
我有这个功能:
public static U? IfNotNull<T, U>(this T? self, Func<T, U?> func)
where T : struct
where U : struct
{
return (self.HasValue) ? func(self.Value) : null;
}
例子:
int? maybe = 42;
maybe.IfNotNull(n=>2*n); // 84
maybe = null;
maybe.IfNotNull(n=>2*n); // null
我希望它适用于隐式可空引用类型以及显式 Nullable<> 类型。这个实现会起作用:
public static U IfNotNull<T, U>(this T? self, Func<T, U> func)
where T : struct
where U : class
{
return (self.HasValue) ? func(self.Value) : null;
}
当然,重载决议不考虑类型约束,所以你不能同时拥有两者。有解决办法吗?
【问题讨论】:
-
不能去掉where子句吗?
-
您可以简单地重命名第二个函数。如果问题出在不同的返回类型...
-
否:第一个函数中的
U必须声明为struct为Nullable'd,并且第二个函数中的U必须声明为class,这样null可以作为U返回。
标签: c# extension-methods nullable monads