对此的答案可能非常明显,但无论如何我都会不屑一顾。
我正在编写一个Range<T>类,在这个过程中我意识到我需要一个比较器。所以,我写了一个通用的比较器,自然地,来自Comparer<T>:
public class Range<T> where T : IComparable
{
// Simplified here for brevity -- actually uses the comparer
public T Min { get; set; }
// Simplified here for brevity -- actually uses the comparer
public T Max { get; set; }
private class DefaultComparer : Comparer<T>
{
public override int Compare(T x, T y)
{
return x == null && y == null
? 0
: x == null
? -1
: y == null
? 1
: x.CompareTo(y);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这一切都运行良好,直到您将 aNullable<T>作为类型传递。例如:
public Range<DateTime?> DateSentFilter { get; set; }
Run Code Online (Sandbox Code Playgroud)
这很糟糕,因为,当然,Nullable<T>没有实现IComparable. 这让我开始思考:为什么不呢?
鉴于比较器通常是如何编写的,为什么不能呢?
有没有对这个东西有深入了解的人有什么想法?是否存在禁止执行此操作的场景?
这是源代码的注释:
// Warning, don't put System.Runtime.Serialization.On*Serializ*Attribute
// on this class without first fixing ObjectClone::InvokeVtsCallbacks
// Also, because we have special type system support that says a a boxed Nullable<T>
// can be used where a boxed<T> is use, Nullable<T> can not implement any intefaces
// at all (since T may not). Do NOT add any interfaces to Nullable!
//
Run Code Online (Sandbox Code Playgroud)
正如它所说,Nullable<T>由于给定的原因无法实现任何接口。
现在,第二个问题是:如果可以,他们会实施吗IComparable?不,帕特里克已经告诉了原因。不是每个T工具都IComparable可以,它只是没有意义。
| 归档时间: |
|
| 查看次数: |
692 次 |
| 最近记录: |