using System; using System.Collections.Generic; namespace TinaX.Systems.Configuration { /// /// IComparer implementation used to order configuration keys. /// 排序用的玩意 /// public class ConfigurationKeyComparer : IComparer { private static readonly string[] _keyDelimiterArray = new[] { ConfigurationPath.KeyDelimiter }; /// /// The default instance. /// public static ConfigurationKeyComparer Instance { get; } = new ConfigurationKeyComparer(); /// /// Compares two strings. /// /// First string. /// Second string. /// Less than 0 if x is less than y, 0 if x is equal to y and greater than 0 if x is greater than y. public int Compare(string x, string y) { var xParts = x?.Split(_keyDelimiterArray, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty(); var yParts = y?.Split(_keyDelimiterArray, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty(); // Compare each part until we get two parts that are not equal for (int i = 0; i < Math.Min(xParts.Length, yParts.Length); i++) { x = xParts[i]; y = yParts[i]; var value1 = 0; var value2 = 0; var xIsInt = x != null && int.TryParse(x, out value1); var yIsInt = y != null && int.TryParse(y, out value2); int result; if (!xIsInt && !yIsInt) { // Both are strings result = string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } else if (xIsInt && yIsInt) { // Both are int result = value1 - value2; } else { // Only one of them is int result = xIsInt ? -1 : 1; } if (result != 0) { // One of them is different return result; } } // If we get here, the common parts are equal. // If they are of the same length, then they are totally identical return xParts.Length - yParts.Length; } } }