void Ctor() { IComparer comp = null; Int32 result = 0; Test.If.Action.ThrowsException(() => comp = new InternalComparer(null), out ArgumentNullException ex1); Test.If.Value.IsEqual(ex1.ParamName, "compare"); Test.IfNot.Action.ThrowsException(() => comp = new InternalComparer((x, y) => 42), out Exception ex2); result = comp.Compare(0, 1); Test.If.Value.IsEqual(result, 42); }
/// <summary> /// Returns a new instance of <see cref="IComparer"/> using the given implementation of <see cref="IComparable"/>. /// </summary> /// <typeparam name="T">The type of the objects to compare.</typeparam> /// <returns>A new instance of <see cref="IComparer"/>.</returns> public static IComparer FromIComparable <T>() where T : IComparable { Type type = typeof(T); Object syncRoot = (_cache as ICollection).SyncRoot; IComparer comparer = null; lock (syncRoot) { if (_cache.ContainsKey(type)) { comparer = _cache[type] as IComparer; } } if (comparer == null) { Comparison compare = (x, y) => { T _x = (T)x; T _y = (T)y; if (_x == null && _y == null) { return(0); } if (_x != null && _y != null) { return(_x.CompareTo(_y)); } return(_x != null ? 1 : -1); }; comparer = new InternalComparer(compare); lock (syncRoot) { if (!_cache.ContainsKey(type)) { _cache.Add(type, comparer); } } } return(comparer); }
/// <summary> /// Returns a new instance of <see cref="IComparer{T}"/> using the given implementation of <see cref="IComparable{T}"/>. /// </summary> /// <typeparam name="T">The type of the objects to compare.</typeparam> /// <returns>A new instance of <see cref="IComparer{T}"/>.</returns> public static IComparer <T> FromIComparableT <T>() where T : IComparable <T> { Type type = typeof(T); Object syncRoot = (_cacheT as ICollection).SyncRoot; IComparer <T> comparer = null; lock (syncRoot) { if (_cacheT.ContainsKey(type)) { comparer = _cacheT[type] as IComparer <T>; } } if (comparer == null) { Comparison <T> compare = (x, y) => { if (x == null && y == null) { return(0); } if (x != null && y != null) { return(x.CompareTo(y)); } return(x != null ? 1 : -1); }; comparer = new InternalComparer <T>(compare); lock (syncRoot) { if (!_cacheT.ContainsKey(type)) { _cacheT.Add(type, comparer); } } } return(comparer); }