|
using System;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace CodeProject
{
public static class ObjectExtensions
{
private static Regex formatSpec = new Regex(@"{(?<name>\S+?)(:(?<format>.*?))?}");
public static string FormatObject(this object self, string format)
{
MatchCollection matches = formatSpec.Matches(format);
if (matches.Count == 0)
return format;
StringBuilder formatBuilder = new StringBuilder();
object[] values = new object[matches.Count];
Type type = self.GetType();
int start = 0;
for (int i = 0; i < matches.Count; ++i)
{
Match match = matches[i];
string name = match.Groups["name"].Value;
string propertyFormat = match.Groups["format"].Value;
PropertyInfo propertyInfo = type.GetProperty(name);
if (propertyInfo == null)
{
throw new FormatException(string.Format(CultureInfo.CurrentUICulture,
"Unknown property {0}.", name));
}
values[i] = propertyInfo.GetValue(self, null);
formatBuilder.Append(format.Substring(start, match.Index - start));
formatBuilder.Append("{");
formatBuilder.Append(i.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(propertyFormat))
formatBuilder.AppendFormat(":{0}", propertyFormat);
formatBuilder.Append("}");
start = match.Index + match.Length;
}
formatBuilder.Append(format.Substring(start));
return string.Format(CultureInfo.CurrentUICulture,
formatBuilder.ToString(), values);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Windows developer with 10+ years experience working in the banking industry.