[英]Comparing generic Nullable types
Imagine I have a generic method involving type T. In terms of usage, T will only ever be of type Nullable<long>
or Nullable<Guid>
. 想象一下,我有一个涉及类型T的通用方法。就用法而言,T永远只能是
Nullable<long>
或Nullable<Guid>
。
Because T is Nullable, I can't impose the type constraint where T : IComparable<T>
on the method. 因为T是可空的,所以我不能在方法上的
where T : IComparable<T>
上施加类型约束。
Given this, what is the most performant way of determining equality between two variables of type T within the method? 鉴于此,在该方法中确定T类型的两个变量之间相等的最有效方法是什么?
I am currently passing in a lambda function like (x, y) => x == y .. but feel there must be a better way. 我目前正在传递像(x,y)=> x == y ..这样的lambda函数,但感觉必须有更好的方法。
If T is always a Nullable, you can pass the underlying type's parameter (instead of Nullable<T>
), and then use Nullable.Compare to do the comparison: 如果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);
...
}
The Comparer<T>.Default
should handle perfectly well nullable values. Comparer<T>.Default
应该可以很好地处理可为空的值。 It does a check about Nullable<>
here so it should handle it. 它会在此处检查有关
Nullable<>
,因此应进行处理。
Note that IComparable<>
is used if you want to know <, >, <=, >=, == (so the order between two elements). 请注意,如果您想知道<,>,<=,> =,==(因此,两个元素之间的顺序),请使用
IComparable<>
。 If you only want Equals
then use IEquatable<>
(and EqualityComparer<T>.Default
). 如果只需要
Equals
则使用IEquatable<>
(和EqualityComparer<T>.Default
)。
Another way to implement - https://dotnetfiddle.net/EBjU54 另一种实现方式-https: //dotnetfiddle.net/EBjU54
Here: I created a proper nullable comparing logic in a separate class to check the equality of two nullable. 在这里:我在一个单独的类中创建了一个适当的可为空的比较逻辑,以检查两个可为空的相等性。 Next, as the anwser of vc74, you pass the underlying type's parameter and use the NullableComparer to check.
接下来,作为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 ;
}
}
}
And calling 并打电话
long? a = 10;
long? b = 10;
var rs = a.Comparexxx<long>(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.