/// <summary> /// 注册尝试从指定流获取指定键的值回调函数。 /// </summary> /// <param name="version">尝试从指定流获取指定键的值回调函数的版本。</param> /// <param name="callback">尝试从指定流获取指定键的值回调函数。</param> public void RegisterTryGetValueCallback(byte version, TryGetValueCallback callback) { if (callback == null) { throw new GXException("Try get value callback is invalid."); } m_TryGetValueCallbacks[version] = callback; }
/// <summary> /// 尝试从指定流获取指定键的值。 /// </summary> /// <param name="stream">指定流。</param> /// <param name="key">指定键。</param> /// <param name="value">指定键的值。</param> /// <returns>从指定流获取指定键的值是否成功。</returns> public bool TryGetValue(Stream stream, string key, out object value) { value = null; using (BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8)) { byte[] header = GetHeader(); if (binaryReader.ReadByte() != header[0] || binaryReader.ReadByte() != header[1] || binaryReader.ReadByte() != header[2]) { return(false); } byte version = binaryReader.ReadByte(); TryGetValueCallback callback = null; if (!m_TryGetValueCallbacks.TryGetValue(version, out callback)) { return(false); } return(callback(binaryReader, key, out value)); } }
/// <summary> /// 尝试从指定流获取指定键的值。 /// </summary> /// <param name="stream">指定流。</param> /// <param name="key">指定键。</param> /// <param name="value">指定键的值。</param> /// <returns>是否从指定流获取指定键的值成功。</returns> public bool TryGetValue(Stream stream, string key, out object value) { value = null; byte[] header = GetHeader(); byte header0 = (byte)stream.ReadByte(); byte header1 = (byte)stream.ReadByte(); byte header2 = (byte)stream.ReadByte(); if (header0 != header[0] || header1 != header[1] || header2 != header[2]) { return(false); } byte version = (byte)stream.ReadByte(); TryGetValueCallback callback = null; if (!m_TryGetValueCallbacks.TryGetValue(version, out callback)) { return(false); } return(callback(stream, key, out value)); }
public static string Format(this string text, TryGetValueCallback tryGetValue, IFormatProvider formatProvider = null) { if (string.IsNullOrEmpty(text)) { return(text); } if (tryGetValue == null) { throw new ArgumentNullException(nameof(tryGetValue)); } formatProvider = formatProvider ?? new DefaultFormatter(); // https://regex101.com/r/sK1tS8/5 var result = Regex.Replace(text, PlaceholderPattern, match => { var name = match.Groups[GroupName.PlaceholderName].Value; var alignment = match.Groups[GroupName.Alignment].Success ? "," + match.Groups[GroupName.Alignment].Value : string.Empty; var formatString = match.Groups[GroupName.FormatString].Success ? ":" + match.Groups[GroupName.FormatString].Value : string.Empty; if (tryGetValue(name, out var value)) { // Apply formatting. return(string.Format(formatProvider, $"{{0{alignment}{formatString}}}", value)); } else { // Reconstruct the format string. return($"{{{name}{alignment}{formatString}}}"); } }); // https://regex101.com/r/zG6tF7/3 result = Regex.Replace(result, "{{(?<contents>.+?)}}", match => $"{{{match.Groups["contents"].Value}}}"); return(result); }