Format

/// <summary>
        /// string formator,replece string.Format
        /// </summary>
        /// <example>string result = StrFormater.Format(@"Hello @Name! Welcome to C#!", new { Name = "World" });///</example>
        /// <param name="template"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Format(this string template, object data)
        {
            return Regex.Replace(template, @"@([\w\d]+)", match => GetValue(match, data));
        }

        static string GetValue(Match match, object data)
        {
            var paraName = match.Groups[1].Value;
            try
            {
                var proper = data.GetType().GetProperty(paraName);
                return proper.GetValue(data).ToString();
            }
            catch (Exception)
            {
                var errMsg = string.Format("Not find'{0}'", paraName);
                throw new ArgumentException(errMsg);
            }
        }
Example:
string result = StrFormater.Format(@"Hello @Name! Welcome to C#!", new { Name = "World" });

Description

string formator,replece string.Format

Details

  • Author: pedoc
  • Submitted on: 8/4/2015 9:45:09 AM
  • Language: C#
  • Type: string
  • Views: 295

Double click on the code to select all.

 

;