using System; namespace Apewer { /// 装箱类。 public sealed class Class : IComparable, IComparable, IComparable> { private bool _hashcode = false; private bool _equals = false; /// 装箱对象。 public T Value { get; set; } /// 创建默认值。 public Class(T value = default, bool tryEquals = true, bool tryHashCode = true) { Value = value; _hashcode = tryHashCode; _equals = tryEquals; } #region Override /// public override int GetHashCode() { if (_hashcode && Value != null) { return Value.GetHashCode(); } return base.GetHashCode(); } /// public override bool Equals(object obj) { if (_equals) { var right = obj as Class; if (right == null) return false; if (Value == null && right.Value == null) return true; if (Value == null && right.Value != null) return false; if (Value != null && right.Value == null) return false; return Value.Equals(right.Value); } return base.Equals(obj); } /// public override string ToString() { if (Value == null) return ""; return Value.ToString(); } #endregion #region IComparable /// /// /// public int CompareTo(object obj) { if (obj != null && obj is T) return CompareTo((T)obj); if (obj != null && obj is Class) return CompareTo(obj as Class); if (Value == null) throw new MissingMemberException(typeof(T).FullName, nameof(Value)); if (!(Value is IComparable)) throw new NotSupportedException(); return ((IComparable)Value).CompareTo(obj); } /// /// /// 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)Value).CompareTo(other); } /// /// /// public int CompareTo(Class other) { if (Value == null) throw new MissingMemberException(typeof(T).FullName, nameof(Value)); if (Value is IComparable) return ((IComparable)Value).CompareTo(other.Value); if (Value is IComparable) return ((IComparable)Value).CompareTo(other.Value); throw new NotSupportedException(); } #endregion #region 运算符。 /// 到 Boolean 的隐式转换,判断 包含值。 /// 当 T 是 Boolean 时,获取 Value。
当 T 是 String 时,判断 Value 不为 NULL 且不为空。
public static implicit operator bool(Class instance) { if (instance == null) return false; var boolean = instance as Class; if (boolean != null) return boolean.Value; var text = instance as Class; if (text != null) return !string.IsNullOrEmpty(text.Value); return instance.NotNull(); } /// 到 T 的隐式转换。 public static implicit operator T(Class instance) { if (instance == null) return default(T); if (typeof(T).Equals(typeof(bool))) return instance.Value; return instance.Value; } /// 从 T 到 的隐式转换。 public static implicit operator Class(T value) => new Class(value); #endregion } }