[英]Generics constraint with nullable types
I've got these very clearly defined methods that internally all call InternalGreaterThan()
but can't find a way - without removing the T
constraint - of making this work for long?
我有这些非常明确定义的方法,它们在内部都调用
InternalGreaterThan()
但找不到一种方法 - 不去除T
约束 - 使这项工作long?
and DataTime?
和数据
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;
}
What are my options here without having to remove the T
constraint (although altering the constraint is of course fine).在不必删除
T
约束的情况下,我有哪些选择(尽管更改约束当然很好)。
You need two separate overloads.您需要两个单独的重载。 One for
T
and one for T?
一个给
T
,一个给T?
. . Eg:
例如:
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);
}
You cannot do that.你不能这样做。 Assuming, you can.
假设,你可以。 Than it is possible to make a call like this:
可以像这样拨打电话:
DateTime? dt = null;
var result = dt.GreaterThan(null);
The system is unable to detect the argument's type.系统无法检测参数的类型。 Which version of the method the system should take?
系统应该采用哪个版本的方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.