Format
string formator,replece string.Format
Source
/// <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" });