简体   繁体   中英

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? and 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).

You need two separate overloads. One for T and one for 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM