using System; namespace Apewer { /// 装箱类。 public sealed class Class : IDisposable // : IComparable, IComparable, IComparable> { /// 值。 public T Value { get; set; } /// 创建装箱实例,值为默认值。 public Class() { } /// 创建装箱实例,值为指定值。 public Class(T value) => Value = value; #region IDisposable /// 如果 实现了 ,则释放 占用的系统资源。 public void Dispose() => RuntimeUtility.Dispose(Value); #endregion #region Override /// public override int GetHashCode() { if (Value != null) return Value.GetHashCode(); return base.GetHashCode(); } /// public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; var right = obj as Class; if (Value.IsNull()) { if (right == null) return true; if (right.Value.IsNull()) return true; return false; } else { if (right == null) return false; if (right.Value.IsNull()) return false; if (ReferenceEquals(Value, right.Value)) return true; return Value.Equals(right.Value); } } /// public override string ToString() { if (Value == null) return null; return Value.ToString(); } #endregion #if ClassCompare #region Compare /// /// public int CompareTo(object obj) { if (typeof(IComparable).IsAssignableFrom(typeof(T))) { var comparable = Value as IComparable; if (comparable.IsNull()) { if (obj is Class bro) { if (bro == null) return 0; if (bro.Value.IsNull()) return 0; return -1; } if (obj.IsNull()) return 0; return -1; } else { if (obj != null && obj is Class bro) return comparable.CompareTo(bro.Value); return comparable.CompareTo(obj); } } throw new NotImplementedException($"类型 {typeof(T).Name} 没有实现 {nameof(IComparable)} 接口。"); } /// /// /// 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 #endif #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 true; } // /// 到 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 } }