[英]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.