using System; using System.ComponentModel; namespace Masuit.Tools.Systems; /// /// 可空对象 /// /// public readonly struct NullObject : IComparable, IComparable { [DefaultValue(true)] private readonly bool _isnull; private NullObject(T item, bool isnull) : this() { _isnull = isnull; Item = item; } public NullObject(T item) : this(item, item == null) { } public static NullObject Null() { return new NullObject(); } public T Item { get; } /// /// 是否是null /// /// public bool IsNull() { return _isnull; } /// /// 隐式转换 /// /// public static implicit operator T(NullObject nullObject) { return nullObject.Item; } /// /// 隐式转换 /// /// public static implicit operator NullObject(T item) { return new NullObject(item); } public override string ToString() { return (Item != null) ? Item.ToString() : "NULL"; } public int CompareTo(object value) { if (value is NullObject nullObject) { if (nullObject.Item is IComparable c) { return ((IComparable)Item).CompareTo(c); } return Item.ToString().CompareTo(nullObject.Item.ToString()); } return 1; } public int CompareTo(T other) { if (other is IComparable c) { return ((IComparable)Item).CompareTo(c); } return Item.ToString().CompareTo(other.ToString()); } public override bool Equals(object obj) { if (obj == null) { return IsNull(); } if (obj is not NullObject nullObject) { return false; } if (IsNull()) { return nullObject.IsNull(); } if (nullObject.IsNull()) { return false; } return Item.Equals(nullObject.Item); } public override int GetHashCode() { if (_isnull) { return 0; } var result = Item.GetHashCode(); if (result >= 0) { result++; } return result; } }