具有可为空类型的泛型约束

时间:2020-09-08 12:11:05

标签: c# .net

我拥有这些定义非常明确的方法,这些方法在内部全部调用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约束(尽管当然可以更改约束)。

2 个答案:

答案 0 :(得分:1)

您需要两个单独的重载。一个用于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);
}

答案 1 :(得分:0)

您不能那样做。假设可以。不可能像这样拨打电话:

DateTime? dt = null;
var result = dt.GreaterThan(null);

系统无法检测到参数的类型。系统应采用哪种版本的方法?