using System; /// <summary>装箱类。</summary> public class Class<T> : IComparable, IComparable<T>, IComparable<Class<T>> { private bool _hashcode = false; private bool _equals = false; /// <summary>装箱对象。</summary> public T Value { get; set; } /// <summary></summary> public bool IsNull { get { return Value == null; } } /// <summary></summary> public bool HasValue { get { return Value != null; } } /// <summary>创建默认值。</summary> public Class(T value = default, bool tryValueEquals = true, bool tryValueHashCode = true) { Value = value; _hashcode = tryValueHashCode; _equals = tryValueEquals; } /// <summary></summary> public override int GetHashCode() { if (_hashcode && Value != null) { return Value.GetHashCode(); } return base.GetHashCode(); } /// <summary></summary> public override bool Equals(object obj) { if (_equals) { if (Value == null && obj == null) return true; if (Value == null && obj != null) return false; if (Value != null && obj == null) return false; return Value.Equals(obj); } return base.Equals(obj); } /// <summary></summary> public override string ToString() { if (Value == null) return null; return Value.ToString(); } /// <summary></summary> /// <exception cref="MissingMemberException"></exception> /// <exception cref="NotSupportedException"></exception> public int CompareTo(object obj) { if (obj != null && obj is T) return CompareTo((T)obj); if (obj != null && obj is Class<T>) return CompareTo(obj as Class<T>); if (Value == null) throw new MissingMemberException(typeof(T).FullName, nameof(Value)); if (!(Value is IComparable)) throw new NotSupportedException(); return ((IComparable)Value).CompareTo(obj); } /// <summary></summary> /// <exception cref="MissingMemberException"></exception> /// <exception cref="NotSupportedException"></exception> public int CompareTo(T other) { if (Value == null) throw new MissingMemberException(typeof(T).FullName, nameof(Value)); if (!(Value is IComparable)) throw new NotSupportedException(); return ((IComparable<T>)Value).CompareTo(other); } /// <summary></summary> /// <exception cref="MissingMemberException"></exception> /// <exception cref="NotSupportedException"></exception> public int CompareTo(Class<T> other) { if (Value == null) throw new MissingMemberException(typeof(T).FullName, nameof(Value)); if (other == null || !other.HasValue) return 1; if (Value is IComparable) return ((IComparable)Value).CompareTo(other.Value); if (Value is IComparable<T>) return ((IComparable<T>)Value).CompareTo(other.Value); throw new NotSupportedException(); } }