[英]Generics constraint with nullable types
我有这些非常明确定义的方法,它们在内部都调用InternalGreaterThan()
但找不到一种方法 - 不去除T
约束 - 使这项工作long?
和数据DataTime?
#nullable enable
public static bool GreaterThan(long? @this, long? value)
{
return InternalGreaterThan(@this, value);
}
public static bool GreaterThan(DateTime? @this, DateTime? value)
{
return InternalGreaterThan(@this, value);
}
public static bool GreaterThan(Version? @this, Version? value)
{
return InternalGreaterThan(@this, value);
}
private static bool InternalGreaterThan<T>(T @this, T value) where T : IComparable<T>?
{
return @this != null && value != null && Comparer<T>.Default.Compare(@this, value) > 0;
}
在不必删除T
约束的情况下,我有哪些选择(尽管更改约束当然很好)。
您需要两个单独的重载。 一个给T
,一个给T?
. 例如:
private static bool InternalGreaterThan<T>(T @this, T value) where T : IComparable<T>
{
return Comparer<T>.Default.Compare(@this, value) > 0;
}
private static bool InternalGreaterThan<T>(T? @this, T? value) where T : struct, IComparable<T>
{
return @this.HasValue && value.HasValue && InternalGreaterThan(@this.Value, value.Value);
}
你不能这样做。 假设,你可以。 可以像这样拨打电话:
DateTime? dt = null;
var result = dt.GreaterThan(null);
系统无法检测参数的类型。 系统应该采用哪个版本的方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.