簡體   English   中英

比較通用Nullable類型

[英]Comparing generic Nullable types

想象一下,我有一個涉及類型T的通用方法。就用法而言,T永遠只能是Nullable<long>Nullable<Guid>

因為T是可空的,所以我不能在方法上的where T : IComparable<T>上施加類型約束。

鑒於此,在該方法中確定T類型的兩個變量之間相等的最有效方法是什么?

我目前正在傳遞像(x,y)=> x == y ..這樣的lambda函數,但感覺必須有更好的方法。

如果T始終是Nullable,則可以傳遞基礎類型的參數(而不是Nullable<T> ),然后使用Nullable.Compare進行比較:

public static void Method<T>(Nullable<T> n1, Nullable<T> n2)
    where T : struct
{
    int comparisonResult = Nullable.Compare(n1, n2);
    ...
}

Comparer<T>.Default應該可以很好地處理可為空的值。 它會在此處檢查有關Nullable<>因此應進行處理。

請注意,如果您想知道<,>,<=,> =,==(因此,兩個元素之間的順序),請使用IComparable<> 如果只需要Equals則使用IEquatable<> (和EqualityComparer<T>.Default )。

另一種實現方式-https: //dotnetfiddle.net/EBjU54

在這里:我在一個單獨的類中創建了一個適當的可為空的比較邏輯,以檢查兩個可為空的相等性。 接下來,作為vc74的答案,您傳遞基礎類型的參數並使用NullableComparer進行檢查。

public static bool Comparexxx<T>(this T? myValue, T? otherValue)
            where T : struct
            { 
                var comparer = new NullableComparer<T>();

                return comparer.Compare(myValue, otherValue) == 1;              
            } 

            public class NullableComparer<T> : IComparer<Nullable<T>>
                  where T : struct
            {

                 public int Compare(Nullable<T> x, Nullable<T> y)
                 {              
                    //Two nulls are equal
                    if (!x.HasValue && !y.HasValue)
                        return 1;

                    //Any object is greater than null
                    if (x.HasValue && !y.HasValue) 
                        return 0;

                    if (y.HasValue && !x.HasValue)
                        return 0;

                    //Otherwise compare the two values
                    return x.Value.Equals(y.Value) ? 1 : 0 ;
                 }

            }
    }

並打電話

long? a = 10;           
long? b = 10;
var rs = a.Comparexxx<long>(b);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM